Mike.Alvarez
Mike.Alvarez

Reputation: 118

Angular route resolver rxjs

My requirement is to have a user switch accounts when they click on a specific link. To fully switch accounts, I need to call two cold http observables and then load the data. The order does matter for all three requests.

  1. First switchAccount$
  2. Second updateSession$

Then I just need to get the pageData$ cold observable. I am currently using a resolver, but having difficulties structuring this with rxjs. I only care about the final page data in my component but I just need to make sure the user switches accounts and the session is updated or the backend api call will fail to get the page data.

I have tried to do the following but it is not working:

resolve(route): Observable<any> {
    const switchAccount$ = this.userService.switch('account2').pipe(last());
    const updateSession$ = this.userService.updateSesh();
    const pageData$ = this.pageService.getData();
    const switchAndUpdate$ = updateSession$.pipe(skipUntil(switchAccount$));


    return pageData$.pipe(skipUntil(switchAndUpdate$.pipe(last()); // problem is that switch account and page data get cancelled somehow??

}

Upvotes: 0

Views: 579

Answers (2)

mickaelw
mickaelw

Reputation: 1513

You can combine observable:

resolve(route): Observable<any> {
    const switchAccount$ = this.userService.switch('account2'); // I think last is not helpful
    const updateSession$ = this.userService.updateSesh();
    const pageData$ = this.pageService.getData();

    return switchAccount$.pipe(
         switchMap(() => updateSession$), // Or I think with margeMap works too
         switchMap(() => pageData$),
         catchError(error => of(error))
    )
}

Upvotes: 1

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20063

You can use switchMap for this:

return obs1$.pipe(
    switchMap(() => obs2$),
    switchMap(() => obs3$),
)

Upvotes: 1

Related Questions