角度视图不从共享服务更新

时间:2013-07-21 18:06:36

标签: caching angularjs service modal-dialog

我需要一些帮助构建我的角度应用程序。

我有两个控制器,'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个问题。

  1. 问题是当Provide.getOffer(id)被调用时:它似乎检测到它是否有本地数据,如果没有本地数据它调用webservice并且一切正常,但是如果存在数据,它试图将它返回到OfferDetailCtrl然后错误。我可以在返回之前调试它的内容,它似乎完好无损,所以我很困惑为什么控制器会接受一个承诺而不是实际的对象。
  2.   

    错误:'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爱听到它:)谢谢你的帮助

1 个答案:

答案 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;

    }