Search code examples
angularjsangularjs-service

Services in AngularJS


I'm learning AngularJS and I've a little problem for services. The official tutorial gives an example for custom services with REST :

angular.module('phonecatServices', ['ngResource']).
    factory('Phone', function($resource){
        return $resource('phones/:phoneId.json', {}, {
            query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
        });
    });

So I made the same code with different names/url and it works.

I would like to pass a parameter to this service (an id in the url). I tried to use $routeParams in it but it didn't work. Finally I found an other way to declare several function in the same service, so I made that :

factory('Article', function($resource) {
    return {
        getList: function(categoryId) {
                return $resource('http://...', {
                    query: {method:'GET', isArray:true}
                });
            }
        }
    })

But it doesn't work for a REST call (with return 'Hello' for example, it's ok).

Do you know how do that ?

Thank you !


Solution

  • It sounds like you are not passing in the parameter into the query function.

    angular.module('Article', ['ngResource']).
        factory('Phone', function($resource){
            return return $resource('http://.../:articleId', {
                    query: {method:'GET', isArray:true}
                });
        });
    });
    

    And then in your controller.

    Article.query({
      articleId : someVar
    });