Home > Blockchain >  Angular error handling and propagation between component and service
Angular error handling and propagation between component and service

Time:12-05

I have a recipe-edit component, in which i submit a form to update a recipe, the code for the .ts file looks something like this

onSubmit(){
    const newRecipe = new Recipe(...params fo the recipe);
      try{
        this.recipeService.updateRecipe(this.id,newRecipe);
      } catch (error){
        console.log(error);
      }
  }

And the recipeService that i call to make the update has an update recipe method that looks like this

updateRecipe(index: number, newRecipe: Recipe){
    return this.http.put<string>('http://localhost:3005/api/recipes/'  index,newRecipe)
      .pipe(
        catchError((error) => {
          return throwError(() => error);
        })
      )
      .subscribe(() => {
        this.recipes[index] = newRecipe;
      })
}

I want to handle the error that i throw in the service, but in the component, so that i can display it in my interface, but this implementation doesnt work, any suggestions on how to improve/fix it?

CodePudding user response:

added this code in service file

updateRecipe(index: number, newRecipe: Recipe){
return this.http.put('http://localhost:3005/api/recipes/'  index,newRecipe);
}

in Component

    onSubmit(){
            const newRecipe = new Recipe(...params fo the recipe);
              try{
                
    this.recipeService.updateRecipe(this.id,newRecipe).subscribe((response:any) => {
        console.log(response)
        },(error:any) => {
        console.log(error)
        });
              } catch (error){
                console.log(error);
              }
    }
     
  • Related