简体   繁体   中英

Angular application not updating list after API call

Angular application doesn't update in real time when I delete

deleteArticle(id) {
    this.articleService.deleteArticle(id).subscribe((article: Article)=>{
        console.log("Article deleted, ", article);
    });
}

The article gets deleted but I then need to refresh the browser to see the result?

Edit: Loading code:

ngOnInit() {
    this.articleService.readArticles().subscribe((articles: Article[])=>{ 
        this.articles = articles;
        console.log(this.articles);
    });
}

You are not updating the articles list.

Change this:

deleteArticle(id){
  this.articleService.deleteArticle(id).subscribe((article: Article)=>{
    console.log("Article deleted, ", article);
  });
}

To this:

deleteArticle(id){
  this.articleService.deleteArticle(id).subscribe((_)=>{
    //find the deleted article index in the list
    const idx: number = this.articles.findIndex(
      (article: Article) => { article.id === id }
    );

    //remove the deleted article from the list
    if(idx !== -1) {
      this.articles.splice(idx, 1);
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM