Angular 6: Property 'catch' does not exist on type 'Observable'?

前端 未结 8 1627
情深已故
情深已故 2020-12-15 18:39

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

相关标签:
8条回答
  • 2020-12-15 19:27

    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';
    
    0 讨论(0)
  • 2020-12-15 19:30

    First of all install the rxjs packages using below command

    npm i rxjs-compat
    

    then import the libraries using

    import 'rxjs/add/operator/catch';
    

    Or import Observable this way:

    import {Observable} from 'rxjs/Rx';
    

    But in this case, you import all operators.

    got from below link https://code-examples.net/en/q/235b329

    0 讨论(0)
  • 2020-12-15 19:34

    Need to import the catch operator

    import 'rxjs/add/operator/catch';
    
    0 讨论(0)
  • 2020-12-15 19:35

    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);
                }
           })
       );
     }
    
    0 讨论(0)
  • 2020-12-15 19:36

    you will need to import all operators you are using.

    import 'rxjs/add/observable/of';
    import 'rxjs/add/observable/throw';
    import 'rxjs/add/operator/catch';
    
    0 讨论(0)
  • 2020-12-15 19:37

    Import the Library with following method and rearrange the code

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

    This worked for me.

    0 讨论(0)
提交回复
热议问题