无法删除[对象数组]的属性“ 1”

时间:2019-11-30 11:06:40

标签: javascript angular typescript

在组件中添加Input的列表:

@Input() usersInput: Section[];

export interface Section {
    displayName: string;
    userId: number;
    title: number;
}

这是值列表:

    0:
     displayName: "بدون نام"
     firstName: null
     lastName: null
     title: 0
     userId: 1
   1:
     displayName: "محمدامین چهاردولی"
     firstName: "محمدامین"
     lastName: "چهاردولی"
     title: 0
     userId: 2

ngAfterViewInit中,我将输入值设置为用户列表:

ngAfterViewInit(): void {
    this.users = this.usersInput;
    if (this.users.length === 0) {
        this.show = false;
    } else {
        this.show = true;
    }
}

这是用户:

users: Section[] = []; 我在html列表中使用它:

<div *ngFor="let item of users" class="d-flex selected-list-items mt-3">
    <div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
        <label>{{item.displayName}}</label>
    </div>
    <div class="col-md-5 col-lg-5 col-xs-5 col-sm-5 col-xl-5">
        <label> {{ getEnumTranslate(item.title)}}</label>
    </div>
    <div class="justify-content-center col-md-2 col-lg-2 col-xs-2 col-sm-2 col-xl-2">
        <button (click)="deleteUser(item.userId)" mat-button>
            <mat-icon aria-label="Delete" color="accent">delete</mat-icon>
        </button>
    </div>
</div>

现在何时需要使用删除按钮:

  <button (click)="deleteUser(item.userId)" mat-button>
       <mat-icon aria-label="Delete" color="accent">delete</mat-icon>
  </button>

ts:

    deleteUser(id: number): void {
    let userModel = {} as Section;
    userModel = this.users.find(x => x.userId === id);
    const index = this.users.indexOf(userModel);
    this.users.splice(index, 1);
    this.emitValueModel.push(
        {
            title: this.user.title,
            userId: this.user.userId
        }
    );
    this.selectedUserId.emit(this.emitValueModel);
    if (this.users.length === 0) {
        this.show = false;
    }
    this.cdref.detectChanges();
}

它告诉我这个错误:

  

错误TypeError:无法删除[对象数组]的属性'1'

出什么问题了???我该如何解决?

3 个答案:

答案 0 :(得分:3)

我也遇到过同样的问题,根据this article,问题是用户数组具有不可配置的属性。我想将角度输入设置为不可配置。当您这样做时: this.users = this.usersInput 您只需将输入的引用传递给this.users。 解决方案是在拼接之前简单地复制输入数组。就您而言:

    this.users = [...this.usersInput];

顺便说一句。在deleteUser方法中执行此操作,而不要在局部变量afterViewInit中执行此操作。您不需要两个指向相同对象的类道具。

答案 1 :(得分:2)

尝试:

deleteUser(id) {
    const index = this.users.findIndex(x => x.userId === id);
    this.users.splice(index, 1);
}

Working Demo

答案 2 :(得分:0)

本文说明了您必须采取的措施才能解决此问题。基本上,您必须指定要删除的数组中索引的元素是可配置的。所以你只需要声明

Object.defineProperty( array , index you want to delete, { configurable : true } );

文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Non_configurable_array_element