简体   繁体   English

Rxjs 使用 concatMap 进行顺序调用

[英]Rxjs make sequential calls using concatMap

I would like to make two sequentially calls (if the first one is completed, call the second one):我想进行两次顺序调用(如果第一次完成,请调用第二次):

My Code is like:我的代码是这样的:

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

First question: is that the right way to make sequential calls?第一个问题:这是进行顺序调用的正确方法吗? Second question: How could I catch the error for the first Call?第二个问题:我如何才能捕捉到第一次通话的错误?

Yes, that is the right way to chain sequential api calls using rxjs.是的,这是使用 rxjs 链接顺序 api 调用的正确方法。 For the second question you may make use of thecatchError operator.对于第二个问题,您可以使用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 is imported from: EMPTY 是从以下位置导入的:

import { EMPTY } from 'rxjs';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM