2017-10-21 102 views
0

我試圖從服務器獲取數據,然後在Ionic頁面中顯示,到目前爲止,我可以獲取沒有問題的數據並在控制檯中檢查。 但是,服務器如何返回給我?訂閱後我如何在離子中填充角度變量?

所以我有這個功能的提供商

public LoadArticle(article_id:any){ 
    let headers = new Headers(); 
    let postData:any; 
    postData = { 
     task: 'GetArticle', 
     article_id: article_id 
    } 

    headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); 
    return this.http.post(this.apiUrl, JSON.stringify(postData),{ headers: headers }); 
    } 

我這樣稱呼它在頁面上我想顯示

constructor(
    public navCtrl: NavController, 
    public controller: WebservicesProvider 
) { 

    } 
this.controller.LoadArticle(1).subscribe(
     data => { 
     let retorno: any; 
     retorno = data; 
     console.log(JSON.parse(retorno._body)); 
     // this.navCtrl.setRoot(AbasPage);   
     // this.article_array = retorno._body.dados; 

     this.articlearray.id = retorno._body.dados.id; 

     this.articleLoaded = true; 
     }, 
     error => { 
     console.log(error) 
     this.controller.endLoading(); 
     }, 
    () => { 
     this.controller.endLoading(); 
     } 
    ); 

如果我寫{{articlearray.id}}頁面HTML文件我得到了一個錯誤

Cannot read property 'id' of undefined 

什麼即時做錯了?

回答

1

如果我寫{{articlearray.id}}在頁面的html文件,我得到一個錯誤

您可以使用安全導航操作:

{{articlearray?.id}} 

這將阻止錯誤,然後在檢索到數據後立即顯示數據。

當模板第一次顯示時,數據尚未檢索,這就是您看到錯誤的原因。在稍後數據被檢索的時間點,Angular的變化檢測將被通知並且數據將出現。