Angular typescript object.assign 不工作(它 return 错误无法读取 'length' of null)
Angular typescript object.assign not working (it return error cannot read 'length' of null)
在文件“a.ts”,它将调用文件“b.ts”
的 handleRequests()
_alerts: Banner[];
obj = {};
postMessage() {
this.obj[this._alerts[0].uuid] = this._alerts;
const data = {
'object': this.obj
};
this.service.handleRequests(stateAction);
}
postMessage();
在文件“b.ts”,
I would like to combine "data.object" with "this.object" and store the result at "this.object" variable.
When initialize object to null, at run time it gives "TypeError: Cannot read property 'length' of null"
object = null ;
handleRequests(data) {
this.object = Object.assign({}, ...this.object, ...data.object);
}
If intialize object to {}, at compile time it gives error "type { } is not an array type."
object = {}
handleRequests(data) {
this.object = Object.assign({}, ...this.object, ...data.object);
}
“b.ts”处的对象初始化是否存在一些问题?
从您的 Object.assign
调用中删除扩展运算符 (...
),如下所示:
object = null;
handleRequests(data) {
this.object = Object.assign({}, this.object, data.object);
}
或者,使用扩展运算符代替 Object.assign
:
object = {};
handleRequests(data) {
this.object = { ...this.object, ...data.object };
}
这是实现相同效果的两种不同方式。选择一个,而不是两个。
另请注意,您不能在 null
.
的对象上使用第二种方法(展开)
在文件“a.ts”,它将调用文件“b.ts”
的 handleRequests()_alerts: Banner[];
obj = {};
postMessage() {
this.obj[this._alerts[0].uuid] = this._alerts;
const data = {
'object': this.obj
};
this.service.handleRequests(stateAction);
}
postMessage();
在文件“b.ts”,
I would like to combine "data.object" with "this.object" and store the result at "this.object" variable.
When initialize object to null, at run time it gives "TypeError: Cannot read property 'length' of null"
object = null ;
handleRequests(data) {
this.object = Object.assign({}, ...this.object, ...data.object);
}
If intialize object to {}, at compile time it gives error "type { } is not an array type."
object = {}
handleRequests(data) {
this.object = Object.assign({}, ...this.object, ...data.object);
}
“b.ts”处的对象初始化是否存在一些问题?
从您的 Object.assign
调用中删除扩展运算符 (...
),如下所示:
object = null;
handleRequests(data) {
this.object = Object.assign({}, this.object, data.object);
}
或者,使用扩展运算符代替 Object.assign
:
object = {};
handleRequests(data) {
this.object = { ...this.object, ...data.object };
}
这是实现相同效果的两种不同方式。选择一个,而不是两个。
另请注意,您不能在 null
.