Angularjs向调用对象返回$http响应
Angularjs to return $http response to caller Object
如何将响应值传递给父对象。在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
引用最内部的函数
相关文章:
- IIS动态HTTP响应标头
- 我如何设置HTTP头“;访问控制允许起源”;用于来自thttpd web服务器的HTTP响应
- Http响应拆分安全问题的XMLHTTPRequest/Response用例的Filter实现
- 使用Express筛选HTTP响应
- 使用不同参数的超级代理缓存缓存 HTTP 响应
- 如何无限期缓存HTTP响应
- 如果HTTP响应为404,脚本标记会被阻塞吗
- Angular 2:用HTTP响应填充复选框列表
- 如何访问您没有访问的HTTP响应的标头't使用javascript通过AJAX发送
- string http响应!=javascript中的相同字符串
- 拦截$resource和$http响应angular
- HTTP响应中出现意外内容
- 如何在java脚本中从http响应生成blob
- 如何记录Apache Cordova应用程序中加载的iframe的http响应
- 如何缓存$http响应以便在angularjs中重用
- 如何将$http响应值传递给另一个函数
- 检查 http 响应代码以显示相应的失败消息
- $http响应拦截器标头
- 在封闭的 python 服务器上的 ajax 请求中获取 0 作为 Http 响应代码
- 如何正确编写 http 响应以便使用 XHR 进度事件侦听器