Ninja
Ninja

Reputation: 211

How to call multiple http call to factory in angularjs?

In my project am using factory which returns list of items as per the service URL passed to that.Now i use the same factory method for all the listing items for example list of users,list of items etc.. but what happens is even i send different URLs to that factory the object is overridden.

It doesn't act as individual methods.I need to fetch different lists through different URLs using single factory and need to show in single page.

please help me with this.Thanks in advance.

Upvotes: 0

Views: 824

Answers (1)

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34227

this is how i would implement a service:

service:

app.factory('MyService', function ($http) {
    var MyService = function () {
    };

    MyService.alertMe = function(message){
        alert(message);
    };

    MyService.getUsers = function(){
        return $http.get('/api/users');
    };

    MyService.createUser = function(user){

        var data = angular.toJson(user);
        return $http.post('/api/users', data);
    };

    return MyService;
});

usage:

app.controller('myCtrl', function($scope, MyService) {

  $scope.click = function() {
    MyService.alertMe('hi from service');
  };
});

example: http://plnkr.co/edit/uf0kx41gsiJBLfZt0O8I?p=preview

Upvotes: 1

Related Questions