Angular2 ActivatedRoute parameter is undefined

前端 未结 1 1608
眼角桃花
眼角桃花 2021-01-07 05:32

Am trying to display the value of activate route param in the screen but fails

In the first component i have

相关标签:
1条回答
  • 2021-01-07 06:17

    When ever you are passing a route parameter, and raise a service call using that parameter, you should use an Observable<params> to subscribe to the activated route in your constructor as below

    category: number = 0;
    constructor(private route:ActivatedRoute, 
                private checklistitemsService: CheckListItemsService) {
    
        this.sub = this.route.params.subscribe(params => {
    
                this.category = + params['category'];
                  ......
    
        });
    }
    

    Then your service call should be made in the ngOnInit()

    ngOnInit(){
          this._checklistitemsService.getAllItems(category)
              .subscribe(res => {
                              this.checklistitems = res
               }
    }
    

    Mistake:

    If you are retrieving the route params in ngOnInit, your components will be loaded before the route value is fetched, so you will find explicit delay and so your this.checklistitems remains without value.

    My solution:

    By retrieving the route parameters, in the constructor, ngOnInit will not execute until the route parameter is retrieved and there by making a service call to get this.checklistitems. Now your component loads correctly.

    0 讨论(0)
提交回复
热议问题