如何在rxjs6中注册路由侦听并更改标题?

时间:2018-09-21 02:35:38

标签: angular router rxjs6

  • rxjs5(angular6应用)中,我使用

    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .map(() => this.activatedRoute)
      .map(route => {
        while (route.firstChild) {
          route = route.firstChild;
        }
        return route;`enter code here`
      })
      .filter(route => route.outlet === 'primary')
      .mergeMap(route => route.data)
      .subscribe((event) => {
        this.titleService.setTitle(event['title'] + '-' + APP_NAME);
        this.appDataLogic.urlChanged();
    });
    
  • 但是在rxjs6中,route{},因此出现错误property firstChild does not exist on type {}

    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(() => { return this.activatedRoute }).pipe(),
      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'] + '-');
    })
    
  • 如何用rxjs6重写它?非常感谢。

1 个答案:

答案 0 :(得分:0)

感谢您的回答,我找到了一个解决方案:

```
 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) => {
      //some code
    })
```

但是我还有另一个问题,它在ngOnInit()的{​​{1}}中使用,app.component.ts是我的根组件,我应该在app.component.ts退订吗?