2017-08-08 51 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范围中的上下文。