【问题标题】:How to chain multiple API calls如何链接多个 API 调用
【发布时间】:2018-12-06 04:57:03
【问题描述】:

我必须链接 2 个 API 调用,在我的组件中我想接收来自上次调用的数据,或者处理任何错误。

这是我的组件,它启动了初始 API 调用。

组件

  public handleSubmit(){
    if(this.loginForm.valid) {
      this.authService.authenticate(this.authRequest)
      .subscribe(
        data => console.log(data),
        error => console.log(error)
      );
    }
  }

服务

我的authenticate 呼叫可能成功或失败。如果失败,我想抛出一个错误,如果成功,它应该开始第二次调用。

authenticate(request: models.AuthenticationRequest) {

    ...

    return this.httpClient.get(environment.auth.ssoAuthorize,
    { 
        headers: headers,
        params: params
    }).pipe(
        map((response: {code: string}) => {
            if(response.code){
                this.getAuthenticationToken(response.code).subscribe(
                    data => { return data }
                )
            }
        }),
        catchError(error => this.handleError(error))
    );
}

这是最后的调用,这个调用接收我必须发送到我的组件的数据。

getAuthenticationToken(code: string): Observable<any> { 

    ...

    return this.httpClient.post(environment.auth.token, {}, {
        headers: headers,
        params: params,
    }).pipe(
        map((response: models.AuthenticationTokenResponse) => {
            if(response.access_token){
                localStorage.setItem('authToken', JSON.stringify(response));
                return true;
            }
            return false;
        }),
        catchError(error => this.handleError(error))
    );
}

【问题讨论】:

    标签: angular api typescript


    【解决方案1】:

    要连接两个 Observable,一个依赖另一个使用 switchMap。 (如果 observables 是独立的,你可以使用 forkJoin。

    SwitchMap 是这样的:

    return observable1.pipe(
          switchMap(res=>{
               //here we can use res
               console.log(res)
               //but we can not return res, we can return
               return observable2(res)
          });
    

    你的情况

    authenticate()
    {
        return this.httpClient.get(environment.auth.ssoAuthorize,
        { 
            headers: headers,
            params: params
        }).pipe(
            switchMap((response: {code: string}) => {
                //we not want return response, we can return:
                if(response.code){
                    return this.getAuthenticationToken(response.code)
                }
                else   //we must return an observable
                {
                    return Observable.of(false);
                }
            }),
            catchError(error => this.handleError(error))
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多