我需要一些帮助构建我的角度应用程序。
我有两个控制器,'OfferListCntrl'(显示商品列表)和'OfferDetailsCntrl'(通过id显示单个商品)以及名为'Offers'的服务/模型。它们分别通过Offers服务连接到两个Web服务,GetOffers(返回商品数量)和GetOffer(返回单个商品),我试图避免调用GetOffer(id),如果已经调用GetOffers(保存服务调用)< / p>
MyApp.factory('Offers', function($http,Config) {
var data=[];
var Offers = {
get: function () {
var promise = $http.get(Config.API_END_POINT + "GetOffers?appID=12",{cache:"true"})
.then(function (response){
data = response.data;
return response.data;
});
return promise;
},
getOffer: function(id) {
var local = _.find(data.Offers, function(offer) { return offer.OfferID == id });
if(local){
console.log("local copy found:" + local.OfferID);
console.log(local.Description);
console.log(local);
return local;
}
else {
var promise = $http.get(Config.API_END_POINT + "GetOffer?appID=12&OfferID=" + id,{cache:"true"})
.then(function (response){
console.log("no local, calling ws");
return response.data;
});
return promise;
}
}
};
return Offers;
});
function OfferDetailCtrl($scope,$http,Offers) {
Offers.get().then(function (asyncData){
$scope.offers = asyncData.Offers;
});
}]);
function OfferDetailCtrl($scope,$routeParams,$http,$location,Offers) {
$scope.offerId = $routeParams.offerId;
Offers.getOffer($scope.offerId).then(function (asyncData){
$scope.offer = asyncData;
});
}
1个问题。
错误:'undefined'不是一个函数(评估 'Offers.getOffer($ scope.offerId).then(function(asyncData){ $ scope.offer = asyncData; 的console.log($ scope.offer); })')OfferDetailCtrl @ http://staging.scanzap.com.au/assets/js/offers/OfferDetailController.js:17
如果有更好的方式我可以做这个id爱听到它:)谢谢你的帮助
答案 0 :(得分:0)
尝试做这样的事情,同时确保注入$ q。
getOffer: function(id) {
var deferred = $q.defer();
var local = _.find(data.Offers, function(offer) { return offer.OfferID == id });
if(local){
console.log("local copy found:" + local.OfferID);
console.log(local.Description);
console.log(local);
deferred.resolve(local;)
}
else {
var promise = $http.get(Config.API_END_POINT + "GetOffer?appID=12&OfferID=" + id,{cache:"true"})
.then(function (response){
console.log("no local, calling ws");
deferred.resolve(response.data);
});
}
return deferred.promise;
}