Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
      }
    });
  }
like image 660
Shubham Verma Avatar asked Jun 21 '18 11:06

Shubham Verma


5 Answers

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);
            }
       })
   );
 }
like image 115
Joakim Avatar answered Oct 19 '22 01:10

Joakim


import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs';
like image 44
Akj Avatar answered Oct 19 '22 00:10

Akj


I am assuming you have migrated to RXJS6 since you have also migrated to angular6.

In RXJS6 use catch Error instead of catch as seen here

  import {catchError } from 'rxjs/operators';
  import { Observable, of } from 'rxjs';
like image 2
prabhat gundepalli Avatar answered Oct 19 '22 01:10

prabhat gundepalli


Import the Library with following method and rearrange the code

import { catchError } from 'rxjs/operators';
return Observable.pipe(catchError =>...);

This worked for me.

like image 2
Susampath Avatar answered Oct 18 '22 23:10

Susampath


Need to import the catch operator

import 'rxjs/add/operator/catch';
like image 1
Sachila Ranawaka Avatar answered Oct 19 '22 00:10

Sachila Ranawaka