Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular TypeError:无法添加属性1,对象不可扩展↵ 在Array.push()_Angular_Typescript_Rxjs - Fatal编程技术网

Angular TypeError:无法添加属性1,对象不可扩展↵ 在Array.push()

Angular TypeError:无法添加属性1,对象不可扩展↵ 在Array.push(),angular,typescript,rxjs,Angular,Typescript,Rxjs,我试图将一些数据添加到数组中,但遇到了不可扩展的错误 组件代码: this._store.select(p => p.collection.workspaceCollectionPages).subscribe((data: CollectionPageDbModel[]) =>{ if(data){ return data.map((collectionPageDbModel)=> { this.collectionPages.push(

我试图将一些数据添加到数组中,但遇到了不可扩展的错误

组件代码:

this._store.select(p => p.collection.workspaceCollectionPages).subscribe((data: CollectionPageDbModel[]) =>{
      if(data){
      return data.map((collectionPageDbModel)=> {

      this.collectionPages.push(collectionPageDbModel) //Getting error on this line while pushing

    });}
我的数据变量中有四个对象,我正试图将其推入collectionPages,但在推入时出现可扩展错误

collectionPage数组,我需要在其中添加更多数据

这是我需要推送的数据

CollectionPageDbModel:

export class CollectionPageDbModel implements IDbModel {
  public id?: number;
  public collection_version_id: number;
  public user_id?: string;
  public name: string;
  public position?: number = 0;
  public contents: string;
  public created_at?: string;
  public updated_at?: string;
  public server_id?: any;

}

有人能帮我解决这个问题吗?

使用object.assign方法复制一个object,然后再试一次

this.collectionPages = Object.assign([], this.collectionPages);
this.collectionPages.push(collectionPageDbModel);

丹尼尔提出的解决方案当然适用于这种情况。原因是每个JS对象都有对象描述符。您可以通过调用Object.getOwnPropertyDescriptorsobj来检查它们,它也适用于数组,因为几乎所有东西都是对象

问题中最可能使用的NGRX存储选择器通过使用object.definePropertiesobj修改对象描述符。这样做是为了防止存储区中的数据在Reducer之外发生任何变异,这种变异也不会改变状态,只会创建一个新的状态

一般情况下,必须克隆要变异的对象:


import { cloneDeep } from 'lodash'

// ...

constructor(private store: Store<any>) {}

someMethod() {
  let someDataFromTheStore = cloneDeep(this.store.select(selectSomeData))
  someDataFromTheStore.myArray.push('...')
}


Object.assign和cloneDeep都不会将描述符传输到新副本


一艘班轮将是:

this.collectionPages=this.collectionPages.slice.pushCollectionPageDmodel;
请将collectionPageDbModel类添加到问题中collectionPages之后会发生什么?在此之后。\ u store.select将新对象推送到collectionPages时,会抛出object not extensible Error是否在任何位置使用preventExtensions或将this.collectionPages对象传递给可能执行此操作的函数?即使在store.select之后,这也会由于javascript事件队列而导致问题。为什么会有return语句?我不认为这是必要的,因为你只是把物体推进去。尝试删除返回,您可以将其用作其他类似选项。collectionPages=[…this.collectionPages,collectionPageDbModel]为什么复制对象可以解决此问题?有js6解决方案吗?@AliSaberi在晚会上迟到了,但我认为状态元素/属性应该是不变的。你有没有试过做一个改变数组的动作?