[英]AngularJS fail to inject a service
我有一個簡單的服務,它從HTTP端點獲取數據並將其發送回控制器。
我還實現了服務中的緩存,但是,我收到此錯誤TypeError: undefined is not a function
控制器中此代碼行上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
};
};
})();
感謝您的時間。
看一下angular-cache文件CHANGELOG.md:“-Angular模塊重命名為angular-cache - DSCacheFactory重命名為CacheFactory “
您將需要更改:
看起來您在實際定義myappApi函數之前已經聲明了myappApi工廠。 嘗試類似:
angular.module('myApp.services',[]).factory('myappApi', ['$http', '$q', '$ionicLoading', 'DSCacheFactory',
function($http, $q, $ionicLoading, DSCacheFactory) {
// myappApi code
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.