首页 > 解决方案 > 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();

标签: node.jsangularmean-stackfork-join

解决方案


首先,您想按顺序调用事物,您不应该使用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


推荐阅读