简体   繁体   English

Angular2:在show component之前等待该服务返回响应

[英]Angular2: wait that service return response before show component

I have an Angular2 component, and i need to populate an attribute of an interface with some data returned by a webservice. 我有一个Angular2组件,我需要使用webservice返回的一些数据填充接口的属性。 I've this code: 我有这个代码:

ngOnInit() {
    this.services.callMyService().subscribe(
       response => this.response = response,
       error => alert(error),
       () => this.initInterface()
    )
}


initInterface() {
    this.myInterface= {
       field1: '',
       field2: 'someData',
       fieldFromService: this.response.field
    };
}

but it seems that component is showed before service has do its job. 但似乎在服务完成工作之前显示组件。 In fact, if i try to access for example to field1, i obtain an error: 事实上,如果我尝试访问例如field1,我会收到一个错误:

error_handler.js:47 EXCEPTION: Cannot read property 'field1' of undefined

what's wrong? 怎么了?

I believe this should work. 我相信这应该有效。

ngOnInit() {
   this.services.callMyService().subscribe(
       response => {this.response = response;
                () => this.initInterface();
               },
       error => alert(error),

)

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM