Home > Enterprise >  angular error handling not working using angular 12
angular error handling not working using angular 12

Time:01-29

I tried angular error manager, I created a posts.component.ts component, I created a posts.service.ts service, I retrieved the posts by api: https://jsonplaceholder.typicode.com/posts, 100 posts, now generate an error, by deleting a non-existent post post n123. when I click on button delete, it does not manage any error either alert or console. list posts

post.component.html

<ul >
    <li  *ngFor="let post of posts">
        <h4>{{ post.title }}</h4>
        <p>{{ post.body }}</p>
        <div align="right">
            <button  (click)="editPost(post)">Edit</button>
            <button  (click)="deletePost(post)">Delete</button> 
       </div>
    </li>
</ul> 

post.service.ts

deletePost(post:any){
     return this.http.delete(this.url   "/"   post.id)
   }

post.component.ts

deletePost(post:any){
    this.postService.deletePost(post)
    .subscribe((response:any)=>{
          let index = this.posts.indexOf(post);
          index=123;
          this.posts.splice(index,1);
        },(error:Response) => {
          if(error.status === 404){
            alert("ce post deja supprimer")
          }else{
            alert("error server");
            console.log(error);
          }
        })
  };

CodePudding user response:

This has nothing to do with your code. The API responds with a HTTP Status Code of 200, even when trying to delete a non existent post. This basically means, that even though nothing can be deleted because it doesn't exist https://jsonplaceholder.typicode.com/ responds that the operation went smoothly.

You can test this using a client of your choice, such as postman. I have saved the request here: https://documenter.getpostman.com/view/11980158/UVeCPTWx You can execute it by clicking on the top right "Run in Postman" and see that it returns with 200.

CodePudding user response:

this.Service.functionName(form)
.subscribe((response:any)=>{
      let index = this.posts.indexOf(post);
      index=123;
      this.posts.splice(index,1);
    },(error:Response) => {
      if(error.status === 404){
        alert("opps! Got error")
      }else{
        alert("error server");
        console.log(error);
      }
    })
  •  Tags:  
  • Related