简体   繁体   中英

router.events doesn't work properly with async in Angular 6

I'm using this code to dynamic title

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(data => this.title = data.title || "");

and view: {{title}}

I wanted to refactor this part (to have async instead subscribe ) So I did:

this.title = this.router.events.pipe(
    filter(event => event instanceof NavigationEn
    mapTo(this.activatedRoute),
    map(route => {
        while (route.firstChild) {
            route = route.firstChild;
        }
        return route;
    }),
    filter(route => route.outlet === "primary"),
    mergeMap(route => route.data),
    pluck("title")
);

and view: {{title | async}} {{title | async}}

But when I open page via URL, or even refresh the page then title is null. It works only when I navigate directly on page (by menu, buttons etc).

I don't know why it was working properly with subscribe and it doesn't with async .

I was even trying only with log, but it's the same issue, title is not appearing at the beginning.

this.title = this.router.events.pipe(
    tap(() => console.log("test"));
)

I ran into the same issue in angular 7 - ie wanting to use async (rather than subscribe ) with this.router.events.pipe .

I solved it using startWith ( https://www.learnrxjs.io/operators/combination/startwith.html ) so I could capture the initial loading event as well as NavigationEnd events.

Here's the relevant code fragment:

  this.router.events.pipe(
    startWith('Initial load'),
    filter(event => event === 'Initial load' || event instanceof NavigationEnd),
    // rest of code here
  );

This sounds like a race condition. The template doesn't always get a chance to subscribe before the router events have completed. You might be able to handle this by replaying the router events so new subscribers (like the async directive) receive events that they may have missed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM