Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular2:在显示组件之前等待服务返回响应_Angular_Angular Services - Fatal编程技术网

Angular2:在显示组件之前等待服务返回响应

Angular2:在显示组件之前等待服务返回响应,angular,angular-services,Angular,Angular Services,我有一个Angular2组件,需要用webservice返回的一些数据填充接口的属性。 我有以下代码: ngOnInit() { this.services.callMyService().subscribe( response => this.response = response, error => alert(error), () => this.initInterface() ) } initInterfac

我有一个Angular2组件,需要用webservice返回的一些数据填充接口的属性。 我有以下代码:

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,您将不会遇到未定义的错误。尝试itMove
this.initInterface()在成功回调中的
this.response=response
行之后。还要尝试在initInterface()之外初始化对象(
this.myInterface={field1:'',field2:'',fieldFromService:'};
),您必须使用*ngIf=“myInterface”在html代码中检查数据是否到达。如果使用*ngIf,您将不会遇到未定义的错误。试试看