我有一个调用API的角度项目。我试图弄清楚如何从返回的结果中引用一个值,并试图通过查看console.log结果来解决它。
这是我的服务电话:
var getUserCampaigns = function(userId){
return $q(function(resolve, reject){
$http.get(API_ENDPOINT.url + '/campaign/user/' + userId).then(function(result){
if(result.status !== 200) {
reject(result);
} else {
resolve(result.data);
console.log('from service: ', result);
}
},function(error){
console.log('There was an error in getting user campaigns: ', error);
reject(error);
});
});
};
以下是API调用返回的内容:
Returned campaign: e
$$state: Object
status: 1
value: Array[2]
0: Object
__v: 0
_id: "583bc4f3bbb04f2b65a34ebc"
description: "This is my description"
endDate: "2016-11-28T05:47:31.261Z"
goalAmount: 23000
mainImage: "image.gif"
ownerId: "58352f5d2632c371aa951be7"
postedOn: "2016-11-28T05:47:31.261Z"
startDate: "2016-11-28T05:47:31.261Z"
subtitle: "subtitle here see"
title: "Title of my campaign"
在我的控制器中,我尝试像这样引用结果:
getUserCampaigns:function(){
this.campaigns = CampaignService.getUserCampaigns(self.userId);
console.log('Value: ' + this.campaigns.title);
}
但我的控制台日志中的“值”显示为“未定义”。
我错过了什么?
答案 0 :(得分:0)
看起来你已经将自己埋没在承诺中。一个典型的模式是服务返回一个承诺,并在控制器中处理该承诺。
首先,服务......明白$ http.get()是一个承诺,你不需要将它包装在另一个承诺中。
app.service('CampaignService', function($http) {
this.getUserCampaigns = function(userId) {
return $http.get(API_ENDPOINT.url + '/campaign/user/' + userId);
};
});
然后在控制器中,您可以处理服务返回的承诺。
app.controller('MainCtrl', function(CampaignService) {
CampaignService.getUserCampaigns(self.userId).then(function(result) {
this.campaigns = result.data;
console.log('Value: ' + this.campaigns.title);
});
});