[英]Angular service do not returning any data in a controller while doing http post
Angular服務在執行http發布時不會在控制器中返回任何數據。
app.controller("letter_active", function ($scope, myService) {
$scope.artist = myService.getReplyType2();
});
app.service('myService', function ($http) {
this.getReplyType2 = function () {
$http.post('file/getReplyType', {})
.success(function (data, status) {
return data;
}).error(function (data, status) {
alert("Error has occured" + status);
});
}
});
需要我幫助的新手
對於異步調用,您需要返回promise
this.getReplyType2 = function() {
var defer = $q.defer();
$http({method: 'POST', url: 'file/getReplyType', data: {}})
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
defer.resolve(data);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
window.data = data;
});
return defer.promise;
}
app.controller("letter_active", function ($scope, myService) {
myService.getReplyType2().then(function(data) {
$scope.artist = data;
});
});
在Angular中,異步服務的典型工作是該服務返回一個Promise對象,並且在控制器中,您可以使用該promise的then/success
方法設置范圍數據:
app.controller("letter_active", function ($scope, myService) {
myService.getReplyType2().then(function(data) {
$scope.artist = data;
});
});
app.service('myService', function ($http) {
this.getReplyType2 = function () {
return $http.post('file/getReplyType', {}).success(function (data, status) {
return data;
}).error(function (data, status) {
alert("Error has occured" + status);
});
}
});
請注意,該getReplyType2
方法現在返回$http.post
調用的結果,這是一個Promise對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.