[英]Get in undefined. Angular Factory & Ionic Framework Error
我正在嘗試在后台使用工廠。 我因注入器錯誤而苦苦掙扎,所以我將工廠放在app.js
而不是在services.js
。 這樣做解決了注入器問題,但是現在當我從app.js
調用factory.get
時,我得到了“ not a function”。
var app = angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers','ngStorage','ngCordova'])
var myService = app.factory('myService', function($localStorage, $scope, $http) {
var items = $http.get("url + $localStorageVariable").then(function(resp) {
if (resp) {
return resp['data.items'];// This will produce promise, not array so can't call directly
console.log("Factory success");
} else {
console.error('ERR', err);
}
});
return {
getAll: function() {
return items;
}
}
});
//later in app.js
myService.getAll().then(function(items){
console.log("Debug. This line in service call") //this doesnt log.
console.log(items)
});
錯誤 :
app.js:50未捕獲的TypeError:myService.getAll不是函數
編輯:
我現在所擁有的是:
var app = angular.module('starter', ['ionic','ionic.service.core', 'starter.controllers','ngStorage','ngCordova'])
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
(function() {
'use strict';
angular
.module('starter', [])
.controller('MainCtrl', MainCtrl)
.factory('myService', myService);
MainCtrl.$inject = ['$scope', 'myService'];
function MainCtrl($scope, myService) {
function getSuccess(response) {
$scope.items = response.data;
}
function getError(response) {
console.log('error');
}
myService.getAll()
.then(getSuccess)
.catch(getError);
}
function myService($http) {
var factory = {
getAll: getAll
};
return factory;
function getAll() {
return $http.get("url");//triple checked, not the isssue
}
}
})();
似乎您沒有將 factory
注入到controller
。 另外, factory
書寫方式有誤。 檢查以下示例:
(function() {
'use strict';
angular
.module('starter', [])
.controller('MainCtrl', MainCtrl)
.factory('myService', myService);
MainCtrl.$inject = ['$scope', 'myService'];
function MainCtrl($scope, myService) {
function getSuccess(response) {
$scope.items = response.data;
}
function getError(response) {
console.log('error');
}
myService.getAll()
.then(getSuccess)
.catch(getError);
}
function myService($http) {
var factory = {
getAll: getAll
};
return factory;
function getAll() {
return $http.get('url');
}
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.