1
我有一个Angular2组件,并且我需要使用webservice返回的一些数据填充接口的属性。 我有这样的代码:Angular2:等待显示组件之前的服务返回响应
ngOnInit() {
this.services.callMyService().subscribe(
response => this.response = response,
error => alert(error),
() => this.initInterface()
)
}
initInterface() {
this.myInterface= {
field1: '',
field2: 'someData',
fieldFromService: this.response.field
};
}
但似乎之前服务已做的工作是组件显示。事实上,如果我尝试访问例如field1,我得到一个错误:
error_handler.js:47 EXCEPTION: Cannot read property 'field1' of undefined
怎么了?
移动'this.initInterface();'在成功呼叫回线'this.response = response'之后。 –
也尝试初始化你的对象('this.myInterface = {field1:'',field2:'',fieldFromService:''};')在你的initInterface() –
之外你必须使用* ngIf =“myInterface” html代码来检查数据是否到达。如果您使用* ngIf,您将不会面临未定义的错误。尝试一下 –