Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch does not exist in type subscription

Tags:

angular

catch does not exist in type subscription in angular4.

this.route.parent.params.subscribe(
      params => {
        const etc = this.service.getEtc()
        Observable.blah.subscribe(results => {
          this.abc = false
        })
          .catch( err => {
            this.service.showErrorAlert('can not find');
          })
    });
like image 638
elin solon Avatar asked Aug 30 '17 11:08

elin solon


2 Answers

As mentioned in the comments the subscribe method returns a subscription, and should usually be the last call in your chain. Try:

Observable.blah
  .catch(err => this.service.showErrorAlert('can not find'))
  .subscribe(results => this.abc = false);

Updated for RXJS 6:

With the introduction of the pipe operator the above code can be replaced verbatim with the following:

import { catchError } from 'rxjs/operators';

Observable.blah
  .pipe(catchError(err => this.service.showErrorAlert('can not find')))
  .subscribe(results => this.abc = false);

However catchError is supposed to be used for error recovery somewhere in the pipeline, for example: there has been an error but you have a default object you can return instead.

To catch an error at the end of the observable chain I would recommend using a different .subscribe overload and passing in an error handler.

Observable.blah
  .subscribe(
    results => this.abc = false,
    err => this.service.showErrorAlert('can not find')
  );
like image 61
UncleDave Avatar answered Nov 14 '22 21:11

UncleDave


You are trying to call catch of your subscribe. That is not possible. You have 2 options:

1:

Observable.blah
    .catch(err => {...})
    .subscribe(results => {
        this.abc = false
    })

2:

Observable.blah
    .subscribe(results => {
        this.abc = false
    },
    err => {
        ...
    })
like image 42
Robin Dijkhof Avatar answered Nov 14 '22 21:11

Robin Dijkhof