首页 > 解决方案 > 如何在 Typescript 中定义数组的数量

问题描述

我需要从数组中删除值。但我无法确定这个数字。我在后端发送一个带有 id 的 DELETE 请求,但是如何在 TypeScript 数组中找到这个值。

数组Click示例

我的代码打字稿

  export class FileService {
public myResults: string[];
public id: number;
Url: string = "";

constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string, 
public dialog: MatDialog ) {
http.get<string[]>(baseUrl + '/getAllFiles').subscribe(result => {
  this.myResults = result;

  console.log(result);
}, error => { console.log('an error occured!'); console.log(error); });
this.Url = baseUrl;
}
public fileDelete(id) {
return this.http.delete(this.Url + '/delete' + id).subscribe(
  data => {

    console.log("DELETE Request is successful ", data);

    const index = this.myResults.indexOf(id)
    this.myResults.splice(index, 1);
  },

我的 HTML 代码

<tr *ngFor="let myResult of myResults;">
    <td>{{ myResult.idPres }}</td>
    <td> {{ myResult.namePres }} </td>
    <td><button  type="button" id="delete" class="btn btn-danger" (click)="fileDelete(myResult.idPres)">Delete</button></td>
  </tr>

标签: typescript

解决方案


Array.prototype.indexOf这样做是不够的。

您需要使用Array.prototype.findIndex

public fileDelete(id) {
    return this.http.delete(this.Url + '/delete' + id).subscribe(
        data => {

            console.log("DELETE Request is successful ", data);
            // objArray is an array containing what we see in your screenShot
            const obj = this.objArray.find(result=> result.idPres === id);
            const fileName = obj.namePres;
            // now fileName is a string so it's safe to find it in a string array with indexOf
            const index = this.myResult.indexOf(fileName);
            this.myResults.splice(index, 1);
        },

推荐阅读