我正在尝试在后台使用工厂。我在注射器错误方面遇到了困难,所以我把工厂放在了app.js
而不是services.js
。这样做可以解决注射器问题,但现在当我从factory.get
拨打app.js
时,我得到了#34;而不是功能"。
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 Uncaught 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
}
}
})();
答案 0 :(得分:0)
您似乎没有将<{1}} 注入您的factory
。此外,您controller
的编写方式也存在错误。请查看以下示例:
factory