Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Angularjs向调用方对象返回$http响应_Javascript_Angularjs_Angular Promise - Fatal编程技术网

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

Javascript Angularjs向调用方对象返回$http响应,javascript,angularjs,angular-promise,Javascript,Angularjs,Angular Promise,如何将响应值传递给父对象。在angularjs中进行http服务调用的调用方?我拥有的是一个基本模型,它将执行以下操作。其思想是basemodel对象实例应该具有响应值。顺便说一句,我尽量避免使用广播和电视 调用对象 定义: }]) 实际的基本模型: 您需要使用自变量,以便可以引用BaseModel的实例变量: function BaseModel($http, $q) { var self = this; self.response = null; /* ... rest of c

如何将响应值传递给父对象。在angularjs中进行http服务调用的调用方?我拥有的是一个基本模型,它将执行以下操作。其思想是basemodel对象实例应该具有响应值。顺便说一句,我尽量避免使用广播和电视

调用对象

定义:

}])

实际的基本模型:


您需要使用自变量,以便可以引用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
引用有关,因为
这个
引用了最内部的函数。

从设计角度来看,构造函数可能不应该发出HTTP请求。我认为构造函数不会发出HTTP请求。在BaseModel中有一个get函数。get函数将执行HTTP请求,这与问题无关,但为什么要创建另一个承诺呢?
$http
已经返回了一个承诺,您可以立即使用它。
BaseModel.$service = ['$http', '$q',
   function ($http, $q) {
       return function () {
           return new BaseModel($http, $q);
       };
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
   };
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 ... */
}