![](/img/trans.png)
[英]How to get data from Angularjs Service Response to Controller Scope Object
[英]How to get response from service on controller
我试图将$ http.post()调用分成一个“ .factory()”,但是想获取在控制器上异步出现的响应。 有办法吗?
控制器:
Login.post($scope.user);
厂:
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
有一个.then(),但我想在控制器上使用它,因此我可以相应地表现。 谢谢!
基本上,您需要返回$http.post
承诺,并且从成功函数中,您可以返回将返回此方法的使用者的数据。 所以,你可以很容易地从控制器及内部调用工厂方法.then
函数的调用,你可以有success
和error
的功能。
码
.factory('Login', function($http, SERVERURL) {
var serverUrl = SERVERURL;
return {
'post': function(user) {
return $http.post(serverUrl + '/login', user).
then(function(response) {
console.log(response);
return response.data; //return data from here
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
})
控制者
Login.post().then(function(data){ //success function
console.log(data)
}, function(error){ //error function
console.log(error);
})
Angular的$http
方法返回一个Promise。
$ http API基于$ q服务公开的延迟/承诺API。
厂
您的方法post
尚未返回任何内容,但是可以很简单地返回通过调用$http.post
创建的Promise:
.factory('Login' , function($http, SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function (user) {
return $http.post(serverUrl + '/login', user)
// ^^^^^^
.then(function (response) {
console.log(response);
return response.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
};
});
控制者
然后通过调用消耗返回的承诺的结果then
就可以了:
Login.post($scope.user).then(function (res) {
// do something with `res`...
});
您可以添加一个回调参数。
.factory( 'Login' , function($http,SERVERURL){
var serverUrl = SERVERURL;
return {
'post' : function(user, callback){
$http.post(serverUrl+'/login', user).
then(function(response) {
console.log(response);
callback(null, response);
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
callback(response);
});
}
};
})
您的控制器将变为:
Login.post($scope.user, function(err, response) {
if(err) {} //do something if there is an error
// or deal with the response
});
要将任何响应返回给控制器,只需执行以下操作:
return {
'post' : function(user){
return $http.post(serverUrl+'/login', user);
}
};
在您的控制器中,您已经调用.then()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.