如何进行两次服务调用并在Angular 6和rxgs中返回响应

时间:2019-02-18 19:28:22

标签: angular rxjs angular6 ngrx angular7

我正在尝试制作两个异步HTTP并保存响应,然后再设置响应。在下面的代码中,我目前只有一个http调用,响应类型为AuthResponse,但是现在我想在刷新令牌方法中添加另一个http调用示例,并传递第二个响应,现在点击我应该有两个响应,一个响应设置为this.setAuth(auth),另一个响应设置为this.setAuth1(auth1)。

**this.http.post<AuthResponse1>(REFRESH_TOKEN_URL_1, null, {
          headers: {
            [HEADER_AUTHORIZATION]: 
     `${AUTHORIZATION_HEADER_PREFIX}${this.getRefreshToken1()}`
          }
        })** - this is call I should add in refresh token method and `response type is AuthResponse1`

    refreshToken(): Observable<AuthResponse | AuthenticationErrorAction> {
        return this.http.post<AuthResponse>(REFRESH_TOKEN_URL, null, {
          headers: {
            [HEADER_AUTHORIZATION]: 
     `${AUTHORIZATION_HEADER_PREFIX}${this.getRefreshToken()}`
          }
        }).pipe(
          tap(auth => this.setAuth(auth)),
          catchError(_ => {
            console.info('refresh token is expired, going to login');
            this.clearStorage();
            window.location.reload(true);
            return of(new AuthenticationErrorAction());
          }));
      }

1 个答案:

答案 0 :(得分:0)

这是一个forkJoin示例。它来自解析器实现。 ForkJoin获取可观察对象的列表,并等待它们返回。它们全部返回后,您可以根据索引提取结果:

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<PersonResolverResult> {
    this.overlay.show();
    return forkJoin(
      this.personService.getPeople(),
      this.personService.getPositions(),
      this.personService.getTypes()
    ).pipe(
      map(x => ({people: x[0], positions: x[1], types: x[2]})),
      finalize(() => this.overlay.hide())
    );
  }