Extract id from url using Angular2

后端 未结 6 938
有刺的猬
有刺的猬 2021-02-03 17:57

Hi I am trying to extract the id part of the url using Angular2.

http://localhost:3000/item/187809

I have been playing around with ActiveRoute

6条回答
  •  情话喂你
    2021-02-03 18:51

    You have multi options to get id

    constructor(private route: ActivatedRoute) { }
    

    1-With the help of params

    const id= this.route.snapshot.params['id'];
    

    or

    const id = this.route.snapshot.params.id // any param name after "params"
    

    2-With the help of paramMap

    const id= this.route.snapshot.paramMap.get('id')
    

    3-subscribe to params (do not forget to unsubscribe)

      private subscription: Subscription
    
      constructor(private route: ActivatedRoute) { }
      ngOnInit(): void {
        this.subscription = this.route.params.subscribe(params => {
          const id = params['id']
        })
      }
    
     //To prevent memory leak
      ngOnDestroy(): void {
        if (this.subscription)
          this.subscription.unsubscribe()
      }
    

提交回复
热议问题