node.js - forkJoin 在 MEAN 应用程序中未将状态 401 作为错误传递
问题描述
在我的 MEAN 应用程序中,我使用 Angular 6 中的 forkJoin 对我的服务器进行顺序调用。
每当请求数据时出现任何错误,我都会传递状态 401 以及错误对象。
我正在订阅请求,但未error
触发该功能。只有data
函数被错误对象触发。
这是我的代码:
TS 文件代码
forkJoin(
this.http.post(url1, obj1).pipe(map((res:Response) => res)),
this.http.post(url2, obj2).pipe(map((res:Response) => res))
).subscribe(
data => {
console.log('Data Called');
},
error => {
console.log('Error Called');
});
节点代码:
res.status(401).send({ error: "error", message: "Oops! Please try again" });
res.end();
解决方案
首先,您想按顺序调用事物,您不应该使用forkJoin
它,它将一次触发所有请求,然后等待所有请求完成。如果您想一一调用它们,请使用concat
import { concat } from 'rxjs/operators';
import { of } from 'rxjs';
//emits 1,2,3
const sourceOne = of(1, 2, 3);
//emits 4,5,6
const sourceTwo = of(4, 5, 6);
//used as static
const example = concat(sourceOne, sourceTwo);
但除此之外。你的问题是为什么错误方法没有被触发。那是因为在处理过程中某个地方抛出错误的那一刻,观察者链就被破坏了。如果你想保护自己免受这种情况的影响,你必须将它缓存在有问题的 observable 上。
forkJoin(
this.http.post(url1, obj1).pipe(map((res:Response) => res)).pipe(catchError(val => of('I caught: ${val}'))),
this.http.post(url2, obj2).pipe(map((res:Response) => res)).pipe(catchError(val => of('I caught: ${val}')))
).subscribe(
data => {
console.log('Data Called');
},
error => {
console.log('Error Called');
});
或者第二个选项是缓存它。但是,如果其中一个可观察对象抛出错误,您将一无所获。
forkJoin(
this.http.post(url1, obj1).pipe(map((res:Response) => res)),
this.http.post(url2, obj2).pipe(map((res:Response) => res))
)
.pipe(catchError(val => of('I caught: ${val}')))
.subscribe(
data => {
console.log('Data Called');
},
error => {
console.log('Error Called');
});
文档清楚地说明了这一点: https ://www.learnrxjs.io/operators/combination/forkjoin.html
推荐阅读
- youtube-api - 按频道 ID 列出的用户电子邮件
- python - TensorFlow 精简版错误!ValueError:Cannot set tensor: Got value of type NOTYPE but expected type FLOAT32 for input 0, name: lstm_input
- javascript - Javascript 问题。如何通过ID选择多个节点,其中ID以相同的单词开头?
- stripe-payments - 条纹支付'client_reference_id'
- python - 列表理解中的双重条件
- python - 在pyppeteer python中填写弹出窗口或提示窗口的形式
- powershell - 使用 SDK 同步 Analysis Services 表格模型
- python - 如何从python中的给定范围生成随机唯一的两个数字集
- swift - 为什么这个脉动动画会移动 x 和 y 位置?
- java - 设计编辑器在项目同步成功之前不可用