When Observable completes without emitting, toPromise() will successfully resolve with undefined.

14 篇文章 0 订阅
2 篇文章 0 订阅

问题原因

When Observable completes without emitting, toPromise() will successfully resolve with undefined.

这句话解释了问题发生的原因,如果是被subscribe的,对于其他res.status 是通过of 返回的,在内层被unsubscribe 的将不会emit 出值,subscribe 里面如果定义了compelte, 则complete 将会被执行。但是是被toPromise(), 没有emit出值但是被complete 的 then 将会接受到undefined

问题描述

自定义拦截器的代码,

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      mergeMap((event) => this.dataHandler(event)),
      catchError((err) => {
        const res = this.errorHandler.handler(err);
        if (res?.status >= 500) {
          return throwError(res);
        } else {
          return of(res);
        }
      }),
      );
  }

component 里面的方法,

getElements(): Promise<any> {
    const params = this.createParams();
    return this.request(params)
      .pipe(map((res: any) => {
        return res || [];
      }), catchError((err) => {
        return of([]);
      }), finalize(() => {
        console.log('complete');
      })).toPromise().then((res) => {
			console.log('result', res);
		})
  }

当请求返回发生错误的时候会被catchError catch 到,然后经过一系列处理后,将res.status >== 500 的当异常抛出,其返回值会被component 中方法的catchError catch 到。但是其他res.status 是通过of 返回的,反而不能进入map operator,而是直接打印了completeresult undefined

附录参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值