2017-06-19 65 views
0

我是Angular 2的新手。我试图从API的响应后呈现模板,但我面临的问题,如模板呈现后的API调用响应。Angular 2同步API调用

我的代码片段的部分是:

ngOnInit() { 
    let productId = this.route.snapshot.params['id']; 

    this.CommonService.fetchData("http://192.168.1.107:9000/api/test/user/userId.json?id=" + productId).subscribe(
    (data) => { 
     this.productData = data[0]; 
     console.log(this.productData); 
    } 
) 
    this.productAdd = this._formBuild.group({ 
    firstName: [this.productData["firstName"]], 
    shortName: [this.productData["shortname"]], 


    }) 
} 
fetchData(url){ 
    return this.http.get(url).map(
    (res) => res.json() 
) 
} 

谁能帮助我?

+0

您能为我们提供了错误? –

+0

'this.productAdd'是数组对象,我为什么要将它分配给FromBuild组? –

+0

它是FormGroup的一个对象productAdd:FormGroup; –

回答

1

我们必须在调用Ajax API之前创建FormGroup。 并将在服务完成后更新数据。

ngOnInit() { 

    this.productAdd = this._formBuild.group({ 
     firstName: '', 
     shortName: '' 
    }); 

    let productId = this.route.snapshot.params['id']; 
    this.CommonService 
    .fetchData("http://192.168.1.107:9000/api/test/user/userId.json?id=" + productId) 
     .subscribe((data) => { 
      const result = data[0]; 
      this.productAdd.patchValue({ 
       firstName: result.firstName, 
       shortName: result.shortName 
      }) 
     }); 

}); 

服务

fetchData(url){ 
    return this.http.get(url) 
     .map((res)=>res.json()); 
} 
+0

它的作品!!!!!!!!!!!谢谢...... –