ActivatedRoute 订阅第一个子参数观察者

ActivatedRoute subscribe to first child parameters observer

我不确定这是否是实现它的最佳方式。如果您有其他意见,请分享。

我必须实现一个多收件箱系统,用户可以将多封电子邮件按不同的收件箱分组。

例如:http://localhost/inbox/personal/ 将显示 personal 收件箱中的电子邮件列表,http://localhost/inbox/business/3 将显示 business 收件箱中的电子邮件列表并突出显示电子邮件编号:3

路线如下所示:

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'personal' // redirect to personal inbox
  },
  {
    path: ':inbox',
    component: InboxContentComponent, // list of emails in :inbox
    children: [
      {
        path: '',
        component: InboxNoSelectedEmailComponent, // no email selected
      },
      {
        path: ':id',
        component: InboxSelectedEmailComponent, // show selected email content
      }
    ]
  }
];

我的问题是 InboxContentComponent。我需要检测收件箱何时更改以及是否选择了电子邮件

  constructor(private route: ActivatedRoute) {
  }
  ngOnInit() {
    this.route.paramMap.subscribe(inbox => {
      console.log('inbox', inbox);
    });
  }

只有当收件箱发生变化时才会发出事件,而不会在电子邮件发生变化时发出。 有没有办法检测子路由参数何时更改?

这样做 this.route.firstChild.paramMap.subscribe(); 只有在组件初始化时路由有第一个子节点时才有效。如果路线是这样 http://localhost/inbox/business/ 那么 this.route.firstChild 就是 null

我能想到的解决方案是像这样定义路由

{
    path: ':inbox/:id',
    component: InboxContentComponent
}

然后检查 InboxContentComponent 是否设置了 :id

有什么想法吗?

为了解决这类问题,我会监听路由器事件并检索我想要的内容。像这样:

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap, tap } from 'rxjs/operators';

// ...
constructor(
    // ...
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.router.events
    .pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute),
      map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      }),
      mergeMap((route) => route.paramMap),
      tap(
        paramMap => console.log('ParamMap', paramMap)
      )
    ).subscribe(
      (paramAsMap) => // Get the params (paramAsMap.params) and use them to highlight or everything that meet your need 
    )
  }

您可以根据需要进行调整。参数?突出显示:无突出显示。