gpt4 book ai didi

javascript - 服务中的 $http 返回 Angularjs 服务中 $$state 的值

转载 作者:行者123 更新时间:2023-12-02 15:51:04 26 4
gpt4 key购买 nike

我编写了一个从服务器获取数据的服务。服务器在本地运行用于测试目的。我面临的问题是数据如果 $http 写入服务中,则在 $$state 内返回。如果相同的 $http 写入 Controller 中,我会得到数据。

如果我输入 res.$$state.value.dat,$$state 不会返回任何数据

aggregate.service('someService',function ($http) 
{

var yearlyAPI = "http://localhost:3000/api";
var yearly =[];
return {
getYearlyAgg : function()
{
if(yearly.length!=0)
{
log("Returning Stored Data For yearly Agg");
return yearly;
}
else
{

var startDate = "2015-08-01";
var endDate = "2015-08-04";

var params = {};
params.startDate = startDate;
params.endDate = endDate;

var yearData = $http.get(yearlyAPI,{
params :params
});

yearly=yearData;
log("Returning New Data For yearly Agg");
log(yearData);
return yearData;
}
}
}; /*Return Ends*/
});

最佳答案

更改代码并尝试以下操作:

aggregate.service('someService',function ($http,$q) 
{

var yearlyAPI = "http://localhost:3000/api";
var yearly =[];
return {
getYearlyAgg : function()
{
if(yearly.length!=0)
{
console.log("Returning Stored Data For yearly Agg");
return $q.when(yearly); //with this you will return a promise if yearly variable contain some object
}
else
{

var startDate = "2015-08-01";
var endDate = "2015-08-04";

var params = {};
params.startDate = startDate;
params.endDate = endDate;

return $http.get(yearlyAPI,{
params :params
}).then(function(result){
yearly.push(result.data); //here you will add your new value to yearly array
return result.data; //you are returning new data after you stored it in yearly variable
});

}
}
}; /*Return Ends*/
});

请与我们分享您的反馈。

关于javascript - 服务中的 $http 返回 Angularjs 服务中 $$state 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31849586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com