Angular 中的删除方法不是删除

问题描述

我正在尝试在我的第一个 Angular 应用程序中执行一个非常基本的 CRUD,但我在使用 Delete 方法时遇到了问题。没有错误id 参数在整个应用程序中正确传递(在控制台中检查),但该项目并未被删除。基本上什么都没发生。

数据库”是我的应用程序的 notes.json 文件夹中名为 assets文件。它包含多个这样的注释:

[
    {
      "id": "id1","title": "First note","description": "This is the description for the first note","categoryId": "1"
    }
]

这些注释放在mat-cardsnote.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% 安全,请检查显示删除成功的后端响应,然后继续从前端删除元素

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...