AngularJS注入服务失败

AngularJS fail to inject a service

本文关键字:失败 服务 注入 AngularJS      更新时间:2024-05-22

我有一个简单的服务,它从HTTP端点获取数据并将其发送回控制器。

我也在服务中实现了缓存,但是,在我的控制器中的这行代码中,我得到了这个错误TypeError: undefined is not a function

myappApi.getItems().then(function(data)

我试图弄清楚为什么我做不到。这是控制器代码:

.controller('ItemsCtrl',['$scope','myappApi',function($scope, myappApi){
    myappApi.getItems().then(function(data){
        $scope.items = data;
    });
}])

正如我在这里使用Ioniframework一样,我是如何在app.js:中注入我的服务的

angular.module('myApp', ['ionic', 'myApp.controllers', 'myApp.services', 'angular-data.DSCacheFactory'])

这是我的服务代码:

(function() {
    'use strict';
    angular.module('myApp.services',[]).factory('myappApi', ['$http', '$q', '$ionicLoading', 'DSCacheFactory', myappApi]);
    function myappApi($http, $q, $ionicLoading, DSCacheFactory) {

        self.itemsCache = DSCacheFactory.get("itemsCache");
        //to re-use expired cached data if no internet connection
        self.itemsCache.setOptions({
            onExpire: function (key, value) {
                getItems()
                    .then(function () {
                        console.log("items items Cache was automatically refreshed.", new Date());
                    }, function () {
                        console.log("Error getting data. Putting expired item back in the cache.", new Date());
                        self.itemsCache.put(key, value);
                    });
            }
        });
        function getItems() {
            var deferred = $q.defer(),
                cacheKey = "items",
                itemsData = self.itemsCache.get(cacheKey);
            if (itemsData) {
                console.log("Found data inside cache", itemsData);
                deferred.resolve(itemsData);
            } else {
                $http.get("services/data.json")
                    .success(function(data) {
                        console.log("Received data via HTTP");
                        self.itemsCache.put(cacheKey, data);
                        deferred.resolve(data);
                    })
                    .error(function() {
                        console.log("Error while making HTTP call.");
                        deferred.reject();
                    });
            }
            return deferred.promise;
        }
        return {
            getItems: getItems
        };
    };
})();

谢谢你抽出时间。

查看角度缓存文件CHANGELOG.md:"-Angular模块重命名为Angular缓存-DSCacheFactory重命名为CacheFactory

您必须更改:

  1. app.js:使用"angular cache"而不是"angular data.DSCacheFactory"
  2. service.js使用"CacheFactory"而不是"DSCacheFactory"

在实际定义myappApi函数之前,您似乎已经声明了myappApi工厂。试试类似的东西:

angular.module('myApp.services',[]).factory('myappApi', ['$http', '$q', '$ionicLoading', 'DSCacheFactory', 
function($http, $q, $ionicLoading, DSCacheFactory) {
  // myappApi code
}]);