我有一个处理用户身份验证的Hprose服务器。我正在尝试编写一个logonService,它在用户登录后返回一个UserInfo对象。在下面的代码中,hprose.HttpClient.login()被异步调用,需要几秒钟,但控制器中的代码在创建logonService实例后仍然继续。因此$ scope.user始终为null,并且永远不会调用logonService.logon()。我试图使用$ http.get,但无法弄清楚如何使用Hprose获取Promise obj,而不是像示例代码中那样使用Http。在谷歌搜索没有提供任何有用的东西。任何人都知道该怎么做?感谢。
var app = angular.module("myApp",[])
.service("logonService", function() {
var httpclient = new hprose.HttpClient("http://testurl.com:4800/webapi/", ["login"]);
httpclient.login("userid", "ppt", function(sid) {
console.log("sid1="+sid);
}
this.logon = function() {
console.log("here I am");
return something;
}
})
.controller("myCtrl", ["logonService", function(logonService) {
var user = logonService.logon();
$scope.user = user;
}
)
答案 0 :(得分:1)
部分问题是myCtrl
中的代码不等待logonService.logon()
的异步结果。此外,我们不知道httpclient.login()
是否会返回承诺或什么。所以我们需要在$ q promise中包含它。
var app = angular.module("myApp",[])
app.service("logonService", function() {
var loginURL = "http://testurl.com:4800/webapi/";
var httpclient = new hprose.HttpClient(loginUrl, ["login"]);
// wrap login fn w/ new $q promise
this.logon = function(userid, ppt) {
return $q(function(resolve,reject){
httpclient.login(userid, ppt, function(sid) {
console.log("sid1="+sid);
// resolve or reject fn based on results passed to callback
if (sid) {
resolve(sid);
} else {
reject('sid wasn\'t defined!');
}
})
}
}
})
app.controller("myCtrl", ["logonService",
function(logonService) {
logonService.logon(userid, ppt).then(function(user){
// assign user to scope only after promise resolved
// 'user' arg will be whatever passed to 'resolve' above
$scope.user = user;
})
.catch(function(e){
console.log('An Error happened: ' + e)
// logon server was down, etc.
})
}
])
Here是AngularJS'的良好参考。 $q
。这将让你知道如何在任何情况下创建Promise。
希望这会帮助你。
答案 1 :(得分:0)
var app = angular.module("myApp",[])
app.service("logonService", function() {
var loginURL = "http://testurl.com:4800/webapi/";
var httpclient = new hprose.HttpClient(loginUrl, ["login"]);
this.logon = function(userid, ppt) {
// the result of httpclient.login is already a promise object.
return httpclient.login(userid, ppt);
}
})
app.controller("myCtrl", ["logonService",
function(logonService) {
logonService.logon(userid, ppt).then(function(user){
// assign user to scope only after promise resolved
// 'user' arg will be whatever passed to 'resolve' above
$scope.user = user;
})
.catch(function(e){
console.log('An Error happened: ' + e)
// logon server was down, etc.
})
}
])
httpclient.login的结果已经是一个promise对象,因此你不需要使用$ q来包装它。