How do I register routing listening in rxjs6 and change the title?

Viewed 171
  • in rxjs5(angular6 app), I use

    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();
    });
    
  • But in rxjs6, route is {} so that has error 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'] + '-');
    })
    
  • How do I rewrite it with rxjs6? thanks a lot.

1 Answers

Thanks for the answers, I found a solution it is :

```
 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
    })
```

But i have a another question, it is used in ngOnInit() in app.component.ts, app.component.ts is my root component, should i unsubscribe it in ngOnDestroy()?

Related