Angular2 ActivatedRoute parameter is undefined

2020-03-07 06:49发布

问题:

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

In the first component i have

<ul *ngFor="let cate of categories;">
  <li (click)="onviewChecklists(cate.id)">
     <a> {{i+1}} {{cate.category}} </a>
  </li>

</ul>

  onviewChecklists(category:string){
     this._router.navigate(["tsafety/checklist-management/categories/items",
       {category:category}])
 }

Now on the second component to where am naviagting i have

category:any;

constructor(
private _router:Router,private activeRoute:ActivatedRoute
 ) {

 }

ngOnInit() {

   this.category = this.activeRoute.snapshot.params['category'];
   console.log(this.category);  //this works
} 
//on this component html {{category}} returns only the first param

In the second component html file when i {{category}} it onl displays the value of the first routing that is

navigate 1 param is checklist display is checklist
navigate 2 param is newcheck  display is checklist

What could be wrong since the console.log() prints the correct value but {{category}} only prints the first value

In the second component ive aso tried

ngOnInit() {
 this.onGetItems(+this.activeRoute.snapshot.params['category']);

 }

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

The onGetItems method is called only once

回答1:

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.