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!!
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)...);
});
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;
});
您需要实例化服务, factory
返回一个构造函数...或者您可以使用.service
代替.factory
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.