Angularjs向调用对象返回$http响应

Angularjs to return $http response to caller Object

本文关键字:http 响应 返回 对象 调用 Angularjs      更新时间:2023-09-26

如何将响应值传递给父对象。在angularjs中调用http服务的调用者?我所拥有的是一个BaseModel,它会像下面这样得到。其思想是基模型对象实例应该具有响应值。顺便说一句,我尽量避免使用广播和on。

调用对象

 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
   };

您需要使用self变量,以便您可以引用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引用最内部的函数