【发布时间】:2019-10-28 15:57:23
【问题描述】:
我的后端有一条使用其 id 删除文章的路线,现在在 Angular 中我有这个文章列表,当我点击它时每一行都有一个按钮我想从数据库中删除这篇文章,很好已经完成了这个但是事情是文章列表没有自动刷新所以删除的文章仍然存在
我有具有 2 种方法的 ArticleService 文件:1 用于获取所有文章(在应用程序启动时调用)和删除文章 1,我希望在成功删除文章后不再显示文章列表那篇文章无需我手动刷新页面
这是我的 ArticleService 文件:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable } from "rxjs";
import { Article } from '../models/article';
@Injectable({
providedIn: 'root'
})
export class ArticleService {
private url: string;
constructor(private _http:HttpClient) {
this.url = 'http://localhost:3000/api/';
}
getArticles(){
let headers = new HttpHeaders().set('Content-Type', 'application/json');
return this._http.get(this.url + 'get-articles', {headers:headers});
}
deteleArticle(id:any){
console.log('Voy a borrar el articulo con id ' + id);
let headers = new HttpHeaders().set('Content-Type', 'application/json');
return this._http.delete(this.url + 'delete-article/' + id, {headers:headers});
}
}
文章组件html:
<div class="actions-container" id="deletebtn">
<button mat-icon-button color="warn" (click)="deleteArticle(data._id)">
<mat-icon>delete_forever</mat-icon>
</button>
</div>
ArticlesListComponent.html
<mat-list>
<mat-list-item *ngFor="let article of data_array">
<app-article [data]='article'></app-article>
</mat-list-item>
</mat-list>
ArticleComponent.ts
import { Component, OnInit,Input } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ArticleService } from '../shared/article.service';
@Component({
selector: 'app-article',
templateUrl: './article.component.html',
styleUrls: ['./article.component.css']
})
export class ArticleComponent implements OnInit {
@Input() data: any;
constructor(
private datePipe: DatePipe,
private _articleService: ArticleService) { }
ngOnInit() {
}
public deleteArticle(id):void{
this._articleService.deteleArticle(id).subscribe(response=>{
console.log(response);
},error=>{
if(<any>error){
console.log(error);
}
});
}
}
和 ArticlesListComponent.ts
import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../shared/article.service';
@Component({
selector: 'app-articles-list',
templateUrl: './articles-list.component.html',
styleUrls: ['./articles-list.component.css'],
providers:[ArticleService]
})
export class ArticlesListComponent implements OnInit {
public data_array = [];
constructor(private articleService: ArticleService) { }
ngOnInit() {
console.log('Article-List component ready.');
this.getAllPost();
}
getAllPost(){
this.articleService.getArticles().subscribe(
result => {
this.data_array = result['articles'];
},
error=>{
console.log(error);
}
);
}
}
如何刷新列表或删除文章后
【问题讨论】:
-
删除文章后,请更新您的
this.data_array。我不确定deteleArticle方法的响应是什么,或者其他替代方法是再次调用服务getArticles(),它将检索您更新的数据并使用输出发射器将其发送回mat-list-item。
标签: javascript angular