Angular 8- 如果第一个 api 调用 returns 没有调用第二个 api

Angular 8- if the first api call returns nothing Call a second api

我必须先调用一个 API,如果值为空数组或 null,我必须调用第二个 API 和 return 来自第二个 [=20] 的值=].在 angular 中执行此操作的最佳方法是什么。我阅读了有关 mergemap、concatmap、forkjoin 等的信息,发现 switchmap 更合适。这是我的方法

 getContact(cdsid: string): Observable<any> {
    const body = JSON.stringify({ cdsid: cdsid });
    this._isLoading = true;
    const endpoint = environment.endpointContacts;
    const endpointUSA = environment.endpointContactUSA + '/get-user-info/' + cdsid;
    return this.http
      .post<any>(endpoint, body)
      .pipe(

        map(
          data => { return of(data[0]) }),

          switchMap(d => {

          return d.pipe(
            map(
              cData => {
         
                if (cData.contact.length > 0) {
                  
                  return cData.contact[0];
                } else {
                  
                  return this.http.get<any>(endpointUSA)                  
                  .pipe(
                     map(
                      data => { return data; }),
                    catchError(
                      (error) => {
                        this._isError = true;
                        return EMPTY;
                      }),
                    finalize(() => {                     
                      this._isError = false;
                    })
            
                  );

                }

              }
            )
          )

        }),

        catchError(
          (error) => {
            this._isError = true;
            return EMPTY;
          }),

        finalize(() => {
            this._isError = false;
        })

      );
  }

但是上述方法没有 return 来自第二个 API 的数据,尽管第一个有一个空数组作为结果。我在这里做错了什么?

你的管道看起来有点乱。请尝试以下操作:


this.http.post<any>(endpoint, body).pipe(
  // Success response.
  // Use switchMap; because we're gonna return another Observable in case of error
  switchMap(data => {
     if(data == null || (Array.isArray(data) && data.length == 0) ) {
        return this.get<any>(endpointUSA)
     } else {
        // Success, everything went nice so rewrap data into an observable
        return of(data);
     }
  }),
  // Handle http errors? do you desire to call the second endpoint in case of http error? you can do it! or not, it's up to you
  catchError(error => this.http.get<any>(endpointUSA))   
);