Reputation: 201
I'm new to angular and I am trying to structure my app following https://github.com/angular-app/angular-app
The issue is when I defined my factory and controller... app.service
angular.module("app.service", [])
.factory('currencyService', function ($http, $q) {
var getCurrency = function () {
var deferred = $q.defer();
$http({
url: baseUrl + "currency/GetAll/",
method: "GET"
}).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
});
return deferred.promise;
}
});
controller :
angular.module('vendor.controller.edit',
[
"acute.select",
"ui.bootstrap",
"ngRoute",
"app.service"
])
.controller('vendorEditCtrl', ["$scope", "$routeParams", "$http", "$modal","currencyService", function ($scope, $routeParams, $http, $modal, currencyService) {
...
}
The issue is that inside the controller currencyService
is undefined...
any idea why?
Thanks for anyone who can help!!
Upvotes: 1
Views: 8050
Reputation: 7521
A factory is a method that is called to generate the service, so Angular calls it then uses the return value to register your service. In your example, you are not returning the function itself. This should fix the problem:
.factory('currencyService', function ($http, $q) {
var getCurrency = function () {
var deferred = $q.defer();
$http({
url: baseUrl + "currency/GetAll/",
method: "GET"
}).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
});
return deferred.promise;
};
return getCurrency;
});
Notice I added the line at the end that actually returns the function.
The way it is defined, you would then call it like this:
.controller("myController", ["currencyService", function(currencyService) {
currencyService().then(function(result)...);
});
Upvotes: 3
Reputation: 23214
Your factory return at the wrong place, so it return undefined
.
You should do like this:
angular.module("app.service", [])
.factory('currencyService', function ($http, $q) {
var deferred = $q.defer(),
getCurrency = function () {
$http({
url: baseUrl + "currency/GetAll/",
method: "GET"
}).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
});
})
return deferred.promise;
});
Upvotes: 1
Reputation: 2927
You need to instantiate service, factory
returns a constructor... or you can use .service
instead of .factory
Upvotes: 0