Extract id from url using Angular2

后端 未结 6 935
有刺的猬
有刺的猬 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:41

    Subscribing and Unsubscribing to Route Parameters

    1. Make sure you have configured a route that expects a parameter like so:

      {path: 'item/:id', component: SomeItemComponent}
      
    2. Declare a variable for your route subscription. Import ActivatedRoute (not ActiveRoute) and inject it in your component constructor.

       private routeSub: Subscription;
       constructor(private route: ActivatedRoute) { }
      
    3. Inside ngOnInit in the same component, you can access the data in the params observable by subscribing to it like so:

       ngOnInit() {
         this.routeSub = this.route.params.subscribe(params => {
           console.log(params) //log the entire params object
           console.log(params['id']) //log the value of id
         });
       }
      
    4. Inside ngOnDestroy, unsubscribe to prevent memory leaks.

       ngOnDestroy() {
         this.routeSub.unsubscribe();
       }
      

    Update - January 2021

    There is a big difference between route.params and route.queryParams.

    route.params, when subscribed to, returns an object with keys (that come from your route parameters, see step 1) and string values that are provided when navigating to the route. For example:

    example.com/item/1

    {
      itemId: '1'
    }
    

    route.queryParams, when subscribed to, returns an object with keys and string values that come from the query string (wiki) in the URL. For example:

    example.com/welcome?var1=abc&var2=cde

    {
      var1: 'abc',
      var2: 'cde'
    }
    

    route.queryParams will be undefined if a query string is not present in the URL. I believe OP, and some users in the comments have mistakenly used this instead of route.params.

提交回复
热议问题