我有一个场景,我想调用一个API,如果返回200,我想调用另一个API,但我只对第一个被调用的API的响应感兴趣.大概是这样的:

    const http1$ = of('response 1');
    // const http2$ = of('response 2');
    const http2$ = throwError('response 2');
    
    http1$.pipe(
      switchMap((response1) => http2$.pipe(map(() => response1)))
    ).subscribe(response1 => {
      // I need to get response 1 even if http2 fails which, in this case, won't work
      console.log(response1);
    });

我想到的唯一解决方案是让ATM机在点击或在HTTP1的订阅内订阅HTTP2,但这不是一个好做法.

推荐答案

如果我没理解错的话,在map操作员中"输入"catchError应该可以帮你解决这个问题.

沿着这些思路的一些东西

http1$.pipe(
    switchMap((response1) => http2$.pipe(
        map(() => response1)).pipe(
            catchError(() => of(response1))
        )
    )
).subscribe(response1 => {
    // I need to get response 1 even if http2 fails which, in this case, won't work
    console.log(response1);
});

EDIT AFTER THE COMMENT个 相反,如果您想在Http1$返回后触发并忘记Http2$,但对Http2$的结果(忘记部分)完全不感兴趣,并立即返回Http1$的响应,则可以这样进行

// first create a shared stream starting with http1$
const http1Shared$ = http1$.pipe(
    share()
);
// then use the shared stream to create a new stream which will trigger http2$ as soon as http1$ returns
// the use of the shared stream is to make sure http1$ is only called once
// you can catch the error and ignore it using catchError(() => EMPTY)
// EMPTY is an observable that completes immediately without emitting any value and without erroring
const stream2$ = http1Shared$.pipe(
    switchMap(() => http2$),
    catchError(() => EMPTY),
);

// then subscribe to both streams - the first one will be used to process the response from http1$
// the second one will be used to trigger http2$ as soon as http1$ returns but will ignore its response
http1Shared$.subscribe(response1 => {
    // I need to get response 1 even if http2 fails which, in this case, won't work
    console.log(response1);
});
stream2$.subscribe();

Angular相关问答推荐

当try 使用Angular和PrimeNg手动聚焦输入时,我做错了什么?

基于另一个控制值显示值的Angular 数组

角material 17 -如何从Style.scss中的主题中获取原色

无法添加@angular/pwa

有没有其他代码可以用函数的方式写成Angular ?

仅在展示时使用垫式步进器

Angular 如何渲染ngFor?

AOS-如何在向上滚动时不再次隐藏元素

Primeng:安装ANGLE 16.2.0版本

当try 关闭浏览器选项卡时显示alert 时,我是否可以捕获用户是否取消警告

Angular APP_INITIALIZER 中的 MSAL 身份验证

有没有办法订阅部分 BehaviorSubject 值的变化?

在 Angular 14 中找不到命名空间google

不再需要 core-js 了吗?

如何从父路由的组件访问激活的子路由的数据?

如何使用 Bootstrap 4 flexbox 填充可用内容?

获取从(keypress)angular2按下的键

设置 Angular Material Tooltip 的字体大小

Angular 2表单验证重复密码

Angular 4 material表突出显示一行