按下删除按钮后,消息将从数据库中删除,但我必须刷新页面才能看到消息从页面中消失。
dashboard.component.html
<h2 *ngIf="user"> Hello, {{user.username}} </h2>
<a [routerLink]="['/']">Log Out</a>
<form (submit)="createMessage()">
<label>Message</label>
<input type="text" name="message" [(ngModel)]="message.message">
<input type="submit" value="create new message">
</form>
<div *ngFor="let message of messages">
<h1>{{message.userId.username}}</h1>
<h3>{{message.message}}</h3>
<h2 *ngIf="user.username === message.userId.username">
<form (submit) = "delete(message._id)">
<button type="submit" name="" value="">DeleteOne</button>
</form>
</h2>
<hr>
</div>
dashboard.component.ts
export class DashboardComponent implements OnInit {
messages: Message[] =[];
user: User;
message: Message = new Message();
currentId;
constructor(public _user: UserService, public _router:Router,private
_route: ActivatedRoute, private _message: MessageService) {
this.user = _user.currentUser;
this._route.params.subscribe((param)=>{
console.log("task details url id is: ", param.id);
this.currentId = param.id;
})
}
delete(val) {
console.log("delete method!", val);
this._message.delete({id: val})
.then((data)=>{
})
答案 0 :(得分:1)
我猜_message.delete在这里返回一个承诺?您可以做的一件事是,当承诺解决时,重新加载您的数据(已删除的记录不再存在)
<强>这里:强>
delete(val) {
console.log("delete method!", val);
this._message.delete({id: val})
.then((data)=>{
// reload your messages
})
答案 1 :(得分:1)
一旦删除,您可以将其从数组中删除,或者您也可以获取数据并重新初始化数组。
delete(val) {
this._message.delete({id: val})
.then((data)=>{
this.messages.remove(this.messages.findIndex((message => message._id === val));
});
}
答案 2 :(得分:0)
您的消息未从UI中删除的原因是您的消息数组未更新。为此,您有两个选择: