user332951
user332951

Reputation: 409

Angularjs to return $http response to caller Object

How can I pass the response value to the parent object. The invoker who make the http service call in angularjs? What I have is a BaseModel where it will do the get like following. The idea is basemodel object instance should have the reponse values. BTW i am trying to avoid to use broadcast and on.

To invoke the object

 model = new BaseModel();
 model.get();

Definition:

BaseModel.$service = ['$http', '$q',
   function ($http, $q) {
       return function () {
           return new BaseModel($http, $q);
       };

}];

the actual BaseModel:

function BaseModel($http, $q) {
   var q = $q.defer();
   this.http = $http;
   this.response = null // this is to hold the response value
   this.get = function () {
       var request = this.http({
           url: 'http://blahblah.com?a=1&b=2',
           method: "GET",
       });
       request.success(function (response) {
           q.resolve(response);
       });

       q.promise.then(
           function(response){
               console.log(response, ' got response');
               //the idea is to have this.response = response
               return response;
           }
       );
       return q.promise
   };

Upvotes: 0

Views: 283

Answers (1)

user9903
user9903

Reputation:

You need to use a self variable so you can refer to the BaseModel's instance variables:

function BaseModel($http, $q) {
  var self = this;
  self.response = null;
  /* ... rest of code ... */

    q.promise.then(function (response) {
      console.log(response, ' got response');
      self.response = response;
    });

  /* ... rest of code ... */
}

The issue isn't angularjs related ,it's related to how objects work in JavaScript and how you have to create a separate self reference because this refers to the inner-most function.

Upvotes: 1

Related Questions