问题描述
我正在尝试在我的第一个 Angular 应用程序中执行一个非常基本的 CRUD,但我在使用 Delete 方法时遇到了问题。没有错误,id
参数在整个应用程序中正确传递(在控制台中检查),但该项目并未被删除。基本上什么都没发生。
“数据库”是我的应用程序的 notes.json
文件夹中名为 assets
的文件。它包含多个这样的注释:
[
{
"id": "id1","title": "First note","description": "This is the description for the first note","categoryId": "1"
}
]
这些注释放在mat-cards
中note.component.html 的用户界面中。
<div *ngFor="let note of notes">
<mat-card class="note">
<mat-card-header>
<mat-card-title>
{{ note.title }}
</mat-card-title>
</mat-card-header>
<mat-card-content>
<p>
{{ note.description }}
</p>
</mat-card-content>
<button><mat-icon (click)="deleteNote(note.id)">delete</mat-icon></button>
</mat-card>
</div>
然后,在 note.component.ts 中,调用 deleteNote
方法。正如我上面所说,note.id
参数被正确传递。
@Component({
selector: 'app-note',templateUrl: './note.component.html',styleUrls: ['./note.component.scss'],})
export class NoteComponent implements OnInit,OnChanges {
@input() selectedCategoryId: string;
notes: Note[];
constructor(private noteService: NoteService) { }
ngOnInit() {
this.noteService.getNotes().subscribe((result) => this.notes = result);
}
ngOnChanges() {
if (this.selectedCategoryId) {
this.noteService.getFilterednotes(this.selectedCategoryId).subscribe((result) => this.notes = result);
}
}
deleteNote(id:string){
console.log(id);
this.noteService.deleteNote(id).subscribe(data => {console.log(data);});
}
}
export interface Note {
id: string;
title: string;
description: string;
categoryId: string;
}
因此调用该服务并执行以下操作:
@Injectable()
export class NoteService {
readonly baseUrl = "https://localhost:4200";
readonly httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',})
};
deleteNote(id:string)
{
return this.httpClient.delete(this.baseUrl + "/notes/" + id,this.httpOptions).subscribe(data => {console.log(data)});
}
}
因此,出了什么问题?我的直觉告诉我,我使用的 subscribe
方法是错误的,但我尝试了不同的方法,但仍然得到相同的结果。
解决方法
所以问题是您发送了从后端删除该注释的请求,但是在前端您的列表永远不会更新。
deleteNote(id:string){
console.log(id);
let indexToBeRemoved = this.notes.findIndex( (note) => {note.id === id});
if (indexToBeRemoved != -1){
this.notes.splice(indexToBeRemoved,1);
}
this.noteService.deleteNote(id).subscribe(data => {console.log(data);});
}
}
如果您想 100% 安全,请检查显示删除成功的后端响应,然后继续从前端删除元素