如何在Typescript中定义数组数

时间:2018-09-05 08:50:16

标签: 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>

2 个答案:

答案 0 :(得分:0)

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);
        },

答案 1 :(得分:0)

由于使用的是对象数组,因此需要查找包含id的对象的索引。替换为下一个

const index = this.myResults.indexOf({id: id})