Angular 6: Property 'catch' does not exist

2020-02-09 07:20发布

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

8条回答
再贱就再见
2楼-- · 2020-02-09 07:32

Need to import the catch operator

import 'rxjs/add/operator/catch';
查看更多
倾城 Initia
3楼-- · 2020-02-09 07:32

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';
查看更多
闹够了就滚
4楼-- · 2020-02-09 07:42

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';
查看更多
smile是对你的礼貌
5楼-- · 2020-02-09 07:43

This worked for me, I'am using Angular 6.1.0.

import { Observable, Subject, of } from 'rxjs';
import { switchMap, debounceTime, distinctUntilChanged, catchError } from 'rxjs/operators';

this.ofertas = this.subjectPesquisa // Retorno Oferta[]
  .pipe(debounceTime(1000)) // Executa a ação do switchMap após 1 segundo
  .pipe(distinctUntilChanged()) // Apenas executa a ação switchMap se o termo enviado for outro
  .pipe(switchMap((termo: string) => {

    if (termo.trim() === '') {
      // Retornar um observable de array de ofertas vazio.
      return of<Oferta[]>([]);
    }

    console.log('Requisição HTTP para api: ', termo);
    return this.ofertasService.pesquisaOfertas(termo);
  }))
  .pipe(catchError((err: any) => {
    console.log('Erro: ', catchError);
    return of<Oferta[]>([]);
  }));
查看更多
冷血范
6楼-- · 2020-02-09 07:47

Import the Library with following method and rearrange the code

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

This worked for me.

查看更多
Summer. ? 凉城
7楼-- · 2020-02-09 07:51
import 'rxjs/add/operator/catch';

Or import Observable this way:

import {Observable} from 'rxjs';
查看更多
登录 后发表回答