在 Angular 中动态设置页面标题

Setting page title dynamically in Angular

我最近升级到 Angular 6 和 rxjs 6,自升级以来,以下动态设置页面标题的代码不再有效

    ngOnInit(): void {
      this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map((route) => {
         while (route.firstChild) {
           route = route.firstChild;
         };

         return route;
      })
      .filter((route) => route.outlet === 'primary')
      .mergeMap((route) => route.data)
      .subscribe((event) => this.titleService.setTitle(event['title']));
};

这给我一个错误

this.router.events.filter is not a function

我试过将过滤器包裹在管道中,例如

this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))

但是我得到了错误

this.router.events.pipe(...).map is not a function

我已经导入了像

这样的过滤器
import { filter, mergeMap } from 'rxjs/operators';

我在这里错过了什么?

这是pipeable/lettables的正确使用方法。

this.router.events.pipe(
  filter(event => event instanceof NavigationEnd),
  map(() => this.activatedRoute),
  map((route) => {
    while (route.firstChild) {
      route = route.firstChild;
    };

    return route;
  }),
  filter((route) => route.outlet === 'primary'),
  mergeMap((route) => route.data),
).subscribe((event) => this.titleService.setTitle(event['title']));

在 RxJs 6 中,所有运算符都是可管道化的,这意味着它们应该在管道方法调用中使用。更多信息 here

所以你的代码应该是这样的:

   this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute),
      map((route) => {
         while (route.firstChild) {
           route = route.firstChild;
         };

         return route;
      }),
      filter((route) => route.outlet === 'primary'),
      mergeMap((route) => route.data)
).subscribe((event) => this.titleService.setTitle(event['title']));

如果您有更大的应用程序,我建议您查看 rxjs-tslint project,因为它将允许您自动更新代码。