Angular2:在显示组件之前等待服务返回响应
我有一个Angular2组件,需要用webservice返回的一些数据填充接口的属性。 我有以下代码:Angular2:在显示组件之前等待服务返回响应,angular,angular-services,Angular,Angular Services,我有一个Angular2组件,需要用webservice返回的一些数据填充接口的属性。 我有以下代码: ngOnInit() { this.services.callMyService().subscribe( response => this.response = response, error => alert(error), () => this.initInterface() ) } initInterfac
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
怎么了?我认为这应该行得通
ngOnInit() {
this.services.callMyService().subscribe(
response => {this.response = response;
() => this.initInterface();
},
error => alert(error),
)
}我认为这应该行得通
ngOnInit() {
this.services.callMyService().subscribe(
response => {this.response = response;
() => this.initInterface();
},
error => alert(error),
)
}Move
this.initInterface()代码>在成功回调中的this.response=response
行之后。还要尝试在initInterface()之外初始化对象(this.myInterface={field1:'',field2:'',fieldFromService:'};
),您必须使用*ngIf=“myInterface”在html代码中检查数据是否到达。如果使用*ngIf,您将不会遇到未定义的错误。尝试itMovethis.initInterface()代码>在成功回调中的this.response=response
行之后。还要尝试在initInterface()之外初始化对象(this.myInterface={field1:'',field2:'',fieldFromService:'};
),您必须使用*ngIf=“myInterface”在html代码中检查数据是否到达。如果使用*ngIf,您将不会遇到未定义的错误。试试看