[英]How can I encapsulate a call to XMLHttp Request inside a $q promise?
I have the following code in an AngularJS ui-router resolve section. 我在AngularJS ui路由器解析部分中有以下代码。
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
How can I encapsulate this in a $q promise that will return a success or fail if the http request worked? 如何将其封装在$ q承诺中,如果http请求有效,该承诺将返回成功或失败? Also should I place all of this inside a promise or just the part that is getting data?
我还应该将所有这些都放在承诺中还是仅放在获取数据的部分中?
You need to place xmlhttp.send();
您需要放置
xmlhttp.send();
inside a promise. 内在的承诺。 use javascript closure to handle callback and resove the defer object as follows:
使用javascript闭包来处理回调并按如下方式解决defer对象:
function sendRequest($q){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
var defer = $q.defer();
xmlhttp.onreadystatechange = (function(xmlhttp, def) {
return function() {
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
def.resolve(xmlhttp)
}
else
{
def.reject(xmlhttp);
}
}
}
})(xmlhttp, defer);
xmlhttp.send();
return defer.promise;
}
EDIT using the function: 使用以下功能进行编辑 :
sendRequest($q).then(function(xmlHttp){
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
}
,function(xmlHttp){
//error
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.