Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2 ActivatedRoute参数未定义_Angular_Typescript - Fatal编程技术网

Angular2 ActivatedRoute参数未定义

Angular2 ActivatedRoute参数未定义,angular,typescript,Angular,Typescript,我试图在屏幕上显示激活路由参数的值,但失败 在第一部分中,我有 <ul *ngFor="let cate of categories;"> <li (click)="onviewChecklists(cate.id)"> <a> {{i+1}} {{cate.category}} </a> </li> </ul> onviewChecklists(category:string){ thi

我试图在屏幕上显示激活路由参数的值,但失败

在第一部分中,我有

<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}])
 }
在第二个组件html文件中,当i
{{category}
时,它只显示第一个路由的值

navigate 1 param is checklist display is checklist
navigate 2 param is newcheck  display is checklist
既然
console.log()
打印正确的值,但
{{category}
只打印第一个值,那么会出现什么问题

在第二部分中,艾维·麻生太郎尝试了

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

 }

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

onGetItems方法只被调用一次

当您传递路由参数并使用该参数发起服务调用时,您应该使用可观察的
在构造函数中订阅激活的路由,如下所示

category: number = 0;
constructor(private route:ActivatedRoute, 
            private checklistitemsService: CheckListItemsService) {

    this.sub = this.route.params.subscribe(params => {

            this.category = + params['category'];
              ......

    });
}
那么您的服务呼叫应该在ngOnInit()中进行

错误:

如果您在ngOnInit中检索路由参数,则在获取路由值之前将加载组件,因此您将发现显式延迟,因此您的将保持此状态。checklistitems没有值

我的解决方案:


通过检索路由参数,在构造函数中,ngOnInit将不会执行,直到检索到路由参数,然后通过服务调用获取this.checklistitems。现在您的组件已正确加载。

您能否澄清您在屏幕上看到的内容以及在控制台日志中看到的内容。例如,当我使用param checklist屏幕打印导航时是checklist,当我使用param newcheck屏幕打印导航时仍然是checklist,但console.log()打印实际值此行为表明绑定有问题。确保在第二个组件中正确绑定了
类别
。听起来模板中的变量与组件中的变量不同。类别是第二个组件中的变量更新了导航单击的位置问题这可能是原因吗解释有意义吗?是的,我实际上意识到错误是在检索OnInit上的值
category: number = 0;
constructor(private route:ActivatedRoute, 
            private checklistitemsService: CheckListItemsService) {

    this.sub = this.route.params.subscribe(params => {

            this.category = + params['category'];
              ......

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