Rxjs 使用 concatMap 进行顺序调用

Rxjs make sequential calls using concatMap

我想连续调用两个(如果第一个调用完成,调用第二个):

我的代码是这样的:

        myApiClient
        .firstApiCall()
        .pipe(take(1),
            concatMap (firstResult => {
            doSomethingWithResponse(firstResult);
            return myApiClient.secondApiCall();
        }), take(1))
        .subscribe(secondResult => {
            doSomethingWithResponse(firstResult);
        }, error => {
            catchSecondApiCallError(error);
        });

第一个问题:这是进行顺序调用的正确方法吗? 第二个问题:如何捕获第一次调用的错误?

是的,这是使用 rxjs 链接顺序 api 调用的正确方法。对于第二个问题,您可以使用 catchError 运算符。

    myApiClient
    .firstApiCall()
    .pipe(
        take(1),
        catchError(e => {
          console.log('Error caught from first api ', e);
          return EMPTY;
        }),
        concatMap (firstResult => {
          doSomethingWithResponse(firstResult);
          return myApiClient.secondApiCall();
    }), take(1))
    .subscribe(secondResult => {
        doSomethingWithResponse(secondResult);
    }, error => {
        catchSecondApiCallError(error);
    });

EMPTY 导入自:

import { EMPTY } from 'rxjs';