![](/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.