fablexis
fablexis

Reputation: 578

How to read data of $http request inside controller from a service?

I'm trying to save the return value of $http service inside my controller, but I get "undefined" like response

In my controller, I call a service that uses the $http:

//this returns undefined
vm.user_instruments = instruments.getInstruments();

My service:

function instruments($http){
       this.getInstruments = function(){
         $http.get('url/').
          then(function(response) {
            /*this console.log print the response, 
            but this value I can't get it in my controller*/
            console.log(response.data);
            return response.data;
          }, function(error) {
            return error.data;
          });
       }
     }//end service

So, what am I doing wrong? My purpose is that the controller be ignorant of any details of HTTP

Upvotes: 0

Views: 455

Answers (3)

Leibale Eidelman
Leibale Eidelman

Reputation: 3184

you have two options to do this:

1. return the promise to the controller and use the promise in the controller

function service ($http) {
    this.request = function () {
        return $http.request({ /*...*/ });
    };
}

function controller (service) {
    service.request().then(function (resp) {
        console.log(resp);
    });
}

2. send callback to service and return the data to the callback

function service ($http) {
    this.request = function (callback) {
        return $http.request({ /*...*/ }).then(function (resp) {
            callback(null, resp);
        }, function (err) {
            callback(err);
        });
    };
}

function controller (service) {
    service.request(function (err, resp) {
        if (err) return console.log(err);

        console.log(resp);
    });
}

the popular option is to use promises, so use option 1 :)

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

Several problems . First your service function isn't returning anything .... return $http from it.

this.getInstruments = function(){
   // return the request promise
   return  $http.get('url/').
      then(function(response) {            
        return response.data;
      }, function(error) {
        return error.data;
      });
   }

Then in controller assign the scope inside a promise callback:

instruments.getInstruments().then(function(data){
  vm.user_instruments = data
});

Upvotes: 1

Ashok Vishwakarma
Ashok Vishwakarma

Reputation: 689

Try this way

Service:

function instruments($http){
  this.get = function(callback){ 
       $http.get('/url').success(function(res){
            callback(res);
       });
    }
 } /* end service */

Controller:

instruments.get(function(res){
     vm.instruments = res;
});

It should work. PS: typed in mobile.

Upvotes: 0

Related Questions