2017-08-08 80 views
0

出於某種原因,我無法訪問Angular項目中的請求響應。即使我可以在控制檯上打印,我也可以訪問data.statusdata.response,但是當我嘗試data.response.entries時,出現以下問題。無法從角度請求中訪問返回的數據

我的組件:

transportantions: any[]; //this is on the start of my component together with the rest of my variables 

    getTransportations() { 
    let loader = this.loadingController.create({ 
     content: 'Getting data...' 
    }); 
    loader.present(); 
    this.wpApi.getTransportations() 
     .then(function (data) { 
     console.log(data); 
     if (data.status == 200) { 
      this.transportantions = data.response.entries; 
      loader.dismiss(); 
     } else { 
      console.log('Something was wrong. Error status ' + data.status); 
     } 
     }) 
     .catch(function (err) { 
     loader.dismiss(); 
     console.log('something was wrong: ' + err); 
     }); 
    } 

這是console.log(data)

{ 
    "status": 200, 
    "response": { 
    "total_count": "242", 
    "entries": [ 
     { 
     ... 
     }, 
     { 
     ... 
     }, 
     { 
     ... 
     }, 
     ... 
    ] 
    } 
} 

輸出而我得到的錯誤是:

something was wrong: TypeError: Cannot set property 'transportantions' of undefined

+0

檢查'data.response'。你得到了什麼?你的輸出是否正確? –

回答

2
getTransportations() { 
    let loader = this.loadingController.create({ 
     content: 'Getting data...' 
    }); 
    loader.present(); 
    this.wpApi.getTransportations() 
     .then((data) => { // just change the function format 
     console.log(data); 
     if (data.status == 200) { 
      this.transportantions = data.response.entries; 
      loader.dismiss(); 
     } else { 
      console.log('Something was wrong. Error status ' + data.status); 
     } 
     }) 
     .catch(function (err) { 
     loader.dismiss(); 
     console.log('something was wrong: ' + err); 
     }); 
    } 

只是改變功能格式。

將函數(){}格式更改爲this()=> {}格式以訪問'this.transportantions';

更多箭頭功能: https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/

+1

它工作。非常感謝。將會選擇你的,因爲它是第一個。只需要等待7分鐘的時間限制。 – Tasos

+0

謝謝!快樂它的工作:) –

+0

@Tasos即使我同意「你的答案是第一」的邏輯,你應該看看我鏈接的文檔瞭解如何箭頭功能的工作,因爲重要的是要理解爲什麼它與它同時工作它沒有使用簡單的js函數。 – Supamiu

2

你必須使用一個arrow function,而不是一個明確的function,讓你保持當前上下文中function範圍:

getTransportations() { 
    let loader = this.loadingController.create({ 
     content: 'Getting data...' 
    }); 
    loader.present(); 
    this.wpApi.getTransportations() 
     .then((data) => { 
     console.log(data); 
     if (data.status == 200) { 
      this.transportantions = data.response.entries; 
      loader.dismiss(); 
     } else { 
      console.log('Something was wrong. Error status ' + data.status); 
     } 
     }) 
     .catch(function (err) { 
     loader.dismiss(); 
     console.log('something was wrong: ' + err); 
     }); 
    } 

在您的示例中,this未定義,因爲您丟失了function範圍中的上下文。