[英]$http.get doesn't work with REST model using then() function
你們知道,Angular最近棄用了http.get.success,error
函數。 因此,不再建議在您的控制器中使用這種調用:
$http.get("/myurl").success(function(data){
myctrl.myobj = data;
}));
而是使用這種調用:
$http.get("/myurl").then(
function(data) {
myctrl.myobj = data;
},
function(error) {
...
}
問題是,簡單的Spring REST模型無法與此新代碼一起使用。 我最近下載了具有上述舊成功功能和REST模型的示例代碼:
@RequestMapping("/resource")
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
這應該為$http.get()
調用返回一個類似{id:<someid>, content:"Hello World"}
的$http.get()
,但是它什么也沒收到-視圖為空。
我該如何解決這個問題?
傳遞給success()
的第一個(四個)參數是響應的數據(即主體)。
但是傳遞給then()
的第一個(也是唯一的)參數不是數據。 它是完整的HTTP響應,包含數據,標頭,狀態和配置。
所以你真正需要的是
$http.get("/myurl").then(
function(response) {
myctrl.myobj = response.data;
},
function(error) {
...
});
對結果的期望是不同的。 它的響應不是直接的數據對象。
文檔說:
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
響應的屬性是
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
由於需要數據對象,
請轉換為
$http.get("/resource").then(
function(response) {
myctrl.myobj = response.data;
});
然后必須返回一個新的諾言,因此您應該延期處理。
var myApp = angular.module('myApp', []);
myApp.factory('modelFromFactory', function($q) {
return {
getModel: function(data) {
var deferred = $q.defer();
var items = [];
items.push({"id":"f77e3886-976b-4f38-b84d-ae4d322759d4","content":"Hello World"});
deferred.resolve(items);
return deferred.promise;
}
};
});
function MyCtrl($scope, modelFromFactory) {
modelFromFactory.getModel()
.then(function(data){
$scope.model = data;
})
}
這是工作提琴-> https://jsfiddle.net/o16kg9p4/7/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.