Reputation: 23
I use inject
to inject $http
to .factory
here is my code:
'use strict';
app.factory('myService', myService);
function myService () {
let service = {
myFunc: myFunc,
};
return service;
}
myFunc.$inject = ['$http'];
function myFunc ($http) {
$http.get('api/data')
.success((res) => {
return res;
})
.error((e) => {
console.log('error' + e.message);
});
}
but, when I call this function I have error: TypeError: e.get is not a function. What I missed? Thank's.
Upvotes: 0
Views: 1177
Reputation: 588
I would reconfigure your app as follows:
(function () {
"use strict";
angular.module('app').factory('myService', myService);
myService.$inject = ['$http'];
function myService($http) {
function myFunc () {
$http.get('api/data')
.then(function(success){
return response.data;
}, function (failure){
return failure;
});
}
return {
myFunc: myFunc
}
}
})();
What this does is scope your 'myFunc' into the 'myService' factory. So from your controller, you can call myFunc() which is determined by the return statement. Basically, your issue was understanding the scope. I also wrapped the entire factory is a closure and made it minification safe for you. Hope this helps!
Upvotes: 0
Reputation: 4084
Use $inject with myService not with myFunc. so your final code will be like this:
'use strict';
app.factory('myService', myService);
function myService () {
let service = {
myFunc: myFunc,
};
return service;
}
myService.$inject = ['$http']; // replace myFunc with myService
function myFunc ($http) {
$http.get('api/data')
.success((res) => {
return res;
})
.error((e) => {
console.log('error' + e.message);
});
}
Upvotes: 1
Reputation: 2137
I think you should try in that way
app.service('myFuncService', ['$http', function($http) {
// myFunc stuff
}]);
app.factory('myService', ['myFuncService', myService])
function myService(myFuncService) {
let service = {
myFunc: myFuncService,
};
return service;
}
Upvotes: 0