Angularjs将$ http响应返回给调用者Object

时间:2014-08-01 17:30:18

标签: javascript angularjs angular-promise

如何将响应值传递给父对象。在angularjs中调用http服务的调用者?我所拥有的是一个BaseModel,它会像下面这样做。想法是basemodel对象实例应具有响应值。顺便说一句,我试图避免使用广播和。

调用对象

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

定义:

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

}];

实际的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
   };

1 个答案:

答案 0 :(得分:1)

您需要使用自变量,以便可以引用BaseModel的实例变量:

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 ... */
}

问题与angularjs无关,它与对象在JavaScript中的工作方式以及如何创建单独的self引用有关,因为this指的是最内部的函数。