Angular 6:“Observable<Response>"类型上不存在属性“catch"? [英] Angular 6: Property 'catch' does not exist on type 'Observable<Response>'?

查看:30
本文介绍了Angular 6:“Observable<Response>"类型上不存在属性“catch"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我的应用升级到 Angular 6.我正在从 Angular 4 升级,但下面的代码在 Angular 6 中导致错误,在 Angular 4 中它运行良好.

I am upgrading my app to Angular 6. I am upgrading from Angular 4, but the code below is causing errors in Angular 6, where it worked fine in Angular 4.

我遇到的错误:

'typeof Observable' 类型不存在属性 'of'

Property 'of' does not exist on type 'typeof Observable'

错误:'Observable' 类型不存在属性 'catch'

Error: Property 'catch' does not exist on type 'Observable'

我应该如何解决这些错误?

How should I resolve these errors?

  private authInterceptor(observable: Observable<Response>): Observable<Response> {
    return observable.catch((error, source) => {
      if (error.status == 401) {
        this.router.navigateByUrl('/login');
        return Observable.of();
      } else {
        return Observable.throw(error);
      }
    });
  }

推荐答案

由于您将问题标记为 rxjs6,我假设升级到 Angular 6 包括升级到 rxjs6.在这种情况下,它不起作用,因为 observable 对象上的方法现在是可以使用 pipe() 应用的独立运算符.此外,进口也发生了变化.有关详细信息,请参阅迁移指南.

Since you tagged your question rxjs6, I'm assuming the upgrade to Angular 6 includes an upgrade to rxjs6. In that case, it's not working because methods on the observable object are now standalone operators that you can apply using pipe(). Also, imports have changed. See the migration guide for more details.

使用 rxjs6,它应该看起来像这样:

With rxjs6 it should look something like this:

import { Observable, EMPTY, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

private authInterceptor(observable: Observable<Response>): Observable<Response> {
   return observable.pipe(
       catchError( err => {
            if (err.status == 401) {
                this.router.navigateByUrl('/login');
                return EMPTY;
            } else {
                return throwError(err);
            }
       })
   );
 }

这篇关于Angular 6:“Observable&lt;Response&gt;"类型上不存在属性“catch"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆