Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

rxjs - Angular 6: Property 'catch' does not exist on type 'Observable<Response>'?

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.


The errors I am getting:

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

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);
      }
    });
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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);
            }
       })
   );
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...