0

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
   };
3
  • Consturctors should probably not make HTTP requests from a design perspective. Commented Aug 1, 2014 at 17:32
  • I don't think the constructor make http request. In BaseModel there is a get function. That get function will perform HTTP request Commented Aug 1, 2014 at 17:36
  • Not relate to the question, but why create an another promise? The $http already return a promise, you can use it right away. Commented Aug 1, 2014 at 17:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.