多个路由参数 angular 6

Multiple Route parameters angular 6

我有两个参数化路由

 { path: 'mails', component: MailsComponent, canActivate: [AuthGuard] },
 { path: 'mails/:label', component: MailsComponent, canActivate: [AuthGuard] },
{ path: 'mails/folder/:folder', component: MailsComponent, canActivate: [AuthGuard] }

在组件中,我想根据条件获取路由参数。

ngOnInit(): void{ 
    if (this.googleAuth.stateFlag) {
      // labels
      this.route.paramMap.subscribe(route => {
        this.label$ = route.get('label');
        this.googleAuth.selectedEmailLabel(this.label$);
      });
    }
    else {
      // folder
      this.route.paramMap.subscribe(route => {
        this.folder$ = route.get('folder');
        console.log('folder handle:', this.folder$);
        this.googleAuth.selectedEmailFolder(this.folder$);
      });
    }
}

虽然有条件,但是每次执行else block。

这个问题很可能是因为 ngOnInit 在组件的生命周期中只被调用一次,并且组件可以在路由更改时多次使用。尝试订阅 paramMap 一次,并在以下范围内处理逻辑:

ngOnInit(): void{ 
  this.route.paramMap.subscribe(route => {
    if (this.googleAuth.stateFlag) {
      this.label$ = route.get('label');
      ...
    } else {
      this.folder$ = route.get('folder');
      ...
    }
  });
}