我有一个Angular应用程序正在执行:
ngOnInit(): void {
this._translationsService.getSegments()
.subscribe(
tus => this.transUnits = tus,
error => this.errorMessage = <any>error,
this.initialize
);
在initialize()中我有
initialize() {
for (var tu of this.transUnits) {
// try to iterate over array
}
}
我一直在:
Uncaught TypeError: Cannot read property 'length' of undefined
at SafeSubscriber.TranslationEditor.initialize [as _complete] (translation-editor.component.ts:80)
可能是因为数据响应尚未完成。
我应该设置某种超时几毫秒吗?
答案 0 :(得分:1)
问题是,当您通过函数引用时,Javascript不会保留this
参数。您需要将this
绑定到调用ala this.initialize.bind(this)
,或者需要使用箭头函数调用它, 保留结束范围。
ngOnInit(): void {
this._translationsService.getSegments()
.subscribe(
tus => this.transUnits = tus,
error => this.errorMessage = <any>error,
() => this.initialize
);