I am trying to use Jhon Papa's Angular 1 style guide to create a factory in Angularjs. The problem is that when I encapsulate a function in an object and then return this object the function does not get called.
For example
Does not work
angular
.module('movieCore')
.factory('PopularMovies', factory);
factory.$inject = ['$resource'];
function factory($resource) {
var service = {
popularMovies: popularMovies
};
return service;
function popularMovies() {
var token = 'teddybear'; // TBC
return $resource('popular/:movieId', { movieId: '@id' }, {
update: {
method: 'PUT',
headers: { 'authToken': token }
},
get: {
method: 'GET',
headers: { 'authToken': token }
},
query: {
method: 'GET',
headers: { 'authToken': token }
},
save: {
method: 'POST',
headers: { 'authToken': token }
},
remove: {
method: 'DELETE',
headers: { 'authToken': token }
}
});
}
}
If I remove the object which holds the function it works.
angular
.module('movieCore')
.factory('PopularMovies', factory);
factory.$inject = ['$resource'];
function factory($resource) {
var token = 'teddybear'; // TBC
console.log('hey there');
return $resource('popular/:movieId', { movieId: '@id' }, {
update: {
method: 'PUT',
headers: { 'authToken': token }
},
get: {
method: 'GET',
headers: { 'authToken': token }
},
query: {
method: 'GET',
headers: { 'authToken': token }
},
save: {
method: 'POST',
headers: { 'authToken': token }
},
remove: {
method: 'DELETE',
headers: { 'authToken': token }
}
});
};
There is one difference, to access the first example you have to write popularMovies.popularMovies();
in the second you can just write popularMovies()
. Thats why one example work an the other not. because first example returns you an object with popularMovies()
as a member. Second example returns directly the $resource
Switch the order of the return statement and the function. popularMovies
is undefined at the time of return:
angular
.module('movieCore')
.factory('PopularMovies', factory);
factory.$inject = ['$resource'];
function factory($resource) {
function popularMovies() {
var token = 'teddybear'; // TBC
return $resource('popular/:movieId', { movieId: '@id' }, {
update: {
method: 'PUT',
headers: { 'authToken': token }
},
get: {
method: 'GET',
headers: { 'authToken': token }
},
query: {
method: 'GET',
headers: { 'authToken': token }
},
save: {
method: 'POST',
headers: { 'authToken': token }
},
remove: {
method: 'DELETE',
headers: { 'authToken': token }
}
});
}
return {
popularMovies: popularMovies
};
}
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.