Dev*_*r52 13 rxjs typescript angular
我正在尝试将一些数据添加到数组中,但出现不可扩展错误。
组件代码:
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
});}
Run Code Online (Sandbox Code Playgroud)
我的数据变量中有四个对象,我试图将它们推送到 collectionPages 中,但是在推送时出现可扩展错误。
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;
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题吗
小智 30
使用 Object.assign 方法复制对象并重试,
this.collectionPages = Object.assign([], this.collectionPages);
this.collectionPages.push(collectionPageDbModel);
Run Code Online (Sandbox Code Playgroud)
小智 15
当我尝试将数据推送到数组时,我遇到了类似的错误警告。我的解决方案是使用扩展运算符而不是push:
let myarray: any = [];
const data = {
answers: [],
score: 24,
ctime: '',
};
myarray = [...myarray, data]; // used this instead of push
Run Code Online (Sandbox Code Playgroud)
Daniel 提出的解决方案当然适用于这种情况。原因是每个 JS 对象都有的对象描述符。您可以通过调用来检查它们Object.getOwnPropertyDescriptors(obj),它也适用于数组,因为(几乎)一切都是对象。
问题中最有可能使用的 NGRX 存储选择器通过使用Object.defineProperties(obj). 这样做是为了防止 Reducer 之外的 Store 中的数据发生任何变化(它也不会改变状态,只是创建一个新状态)。
在一般情况下,您必须克隆要变异的对象:
import { cloneDeep } from 'lodash'
// ...
constructor(private store: Store<any>) {}
someMethod() {
let someDataFromTheStore = cloneDeep(this.store.select(selectSomeData))
someDataFromTheStore.myArray.push('...')
}
Run Code Online (Sandbox Code Playgroud)
无论Object.assign和cloneDeep描述符不转移到新的副本。
Object.getOwnPropertyDescriptors
| 归档时间: |
|
| 查看次数: |
22890 次 |
| 最近记录: |