1
votes

Comment utiliser du code dans un bloc de code catchError

Je ne connais pas la syntaxe correcte pour cela, comment utiliser un bloc de code dans catchError?

.pipe(
  catchError(self.timelineDates = self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
  // more code...

  )
)

Je veux donc utiliser quelque chose comme ça où je peux attribuer un valeur à timelineDates.

this.budgetService.getBudgetDays(this.startDate, this.finishDate)
        .pipe(
          catchError(res => self.budgetTestService.getBudgetDates(self.startDate, self.finishDate))
        )
        .subscribe(res => {
          console.log('Response = ', res);
          self.timelineBudgetDates = self.processDates(res);
          //self.timelineBudgetDates = res;

        });


1 commentaires

La page de documentation clarifie assez bien l'utilisation. Le fait est que l'argument de catchError doit être une fonction qui reçoit deux arguments: un objet d'erreur et l'observable source.


3 Réponses :


0
votes

catchError a besoin d'une fonction de rappel comme paramètre.

.pipe(
  catchError(() => {
    self.timelineDates = self.budgetTestService.getBudgetDates(self.startDate, self.finishDate
  })
  // more code...
)


0 commentaires

0
votes

catchError est juste une fonction

// RxJS v6+
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));

https://www.learnrxjs.io/operators/error_handling/catch.html

.pipe(
  catchError(error => {
      console.log({error});
     self.timelineDates = self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
  // more code...but return an observable
 return of('some return value, maybe null, maybe a good default');
    }
  )
)


0 commentaires

1
votes

Essayez d'utiliser ce

.pipe(
 catchError(err => {
  self.timelineDates = self.budgetTestService.getBudgetDates(self.startDate, self.finishDate);
  console.error(err.message);
  console.log("Error is handled");
  return throwError("Error thrown from catchError");
 })
 // more code...
)

Apprenez les détails ici https://www.concretepage.com/angular/angular-catcherror


0 commentaires