问题
I have a very simple service and a controller attempting to get some information from it, but I keep getting .methodName is not a function.
Here is the service, apiService.js :
(function (module) {
function api() {
var sharedService = {};
sharedService = {
getAll: function () {
return 'test';
}
};
return sharedService;
}
module.factory("api", api);
}(angular.module("anbud")));
Then I attempt to use my method getAll in the controller, like this:
(function () {
'use strict';
angular.module('anbud')
.controller('BasicExampleCtrl', ['$scope', 'api', function (api, $scope) {
// on successfull request
function onJson(json) {
$scope.data = json;
}
// error getting json
function onError() {
throw 'error getting json';
}
function initialize() {
api.getAll()
.then(onJson, onError);
}
initialize();
}]);
}());
But I get the error:
TypeError: api.getAll is not a function
at initialize (basic-example.js:67)
Any help is appreciated thank you.
回答1:
You have interchanged the dependencies sequence inside controller
factory function, the sequence must be same as they are included in DI array
while injecting in function.
Code
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope, api) { //<- first $scope then api.
回答2:
try it like this:
.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {
来源:https://stackoverflow.com/questions/33673051/typeerror-api-getall-is-not-a-function-service-method-is-not-recognized