2017-06-19 67 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

它的作品!!!!!!!!!!!謝謝...... –