Tôi đang cố gắng sử dụng resolve
trong một $routeProvider
để hiển thị tuyến đường mới chỉ khi yêu cầu $http
hoàn tất. Nếu yêu cầu thành công, lời hứa xuất phát từ $ http.post() được giải quyết và khung nhìn được hiển thị. Nhưng nếu yêu cầu không thành công (hết thời gian chờ hoặc lỗi nội bộ cho ví dụ.), Lời hứa sẽ không bao giờ được giải quyết và chế độ xem sẽ không bao giờ được hiển thị. Làm cách nào tôi có thể xử lý yêu cầu không thành công bằng cách sử dụng resolve
?
Các bộ phận quan trọng nhất của mã này là dưới đây:
app.js
$routeProvider.when('/warrantyResult', {
templateUrl : 'partials/warranty-result.html',
controller : 'WarrantyResultCtrl',
resolve : {
response : [ 'Warranty', function(Warranty) {
return Warranty.sendRequest();
} ]
}
});
controllers.js
angular.module('adocDemo.controllers', []).controller('HomeCtrl', [ '$scope', function($scope) {
} ]).controller('WarrantyCtrl', [ '$scope', '$http', '$location', 'Warranty', function($scope, $http, $location, Warranty) {
$scope.submitWarranty = function() {
$scope.loading = true;
Warranty.setRequestData($scope.data);
$location.path('/warrantyResult');
};
} ]).controller('WarrantyResultCtrl', [ '$scope', 'Warranty', function($scope, Warranty) {
$scope.request = Warranty.getRequestData();
$scope.response = Warranty.getResponseData();
} ]);
services.js
angular.module('adocDemo.services', []).factory('Warranty', [ '$http', '$timeout', function($http, $timeout) {
/**
* This service is used to query the Warranty Webmethod. The sendRequest
* method is automaticcaly called when the user is redirected to
* /warrantyResult route.
*/
var isDataSet = false;
var requestData = undefined;
var responseData = undefined;
return {
setRequestData : function(data) {
//Setting the data
isDataSet = true;
},
getRequestData : function() {
return requestData;
},
sendRequest : function(data) {
if(isDataSet) {
var request = $http.post('url/to/webservice', requestData);
request.success(function(data) {
responseData = data;
});
return request;
}
},
getResponseData : function() {
return responseData;
}
};
} ]);
tôi biết tôi có thể sử dụng lời hứa vòng cuộc gọi $ http và giải quyết nó ngay cả khi yêu cầu là một thất bại, nhưng tôi tự hỏi nếu có một giải pháp đơn giản hơn.
Cảm ơn bạn đã đọc và, hy vọng, giúp đỡ :)
Tùy thuộc vào cách bạn muốn ứng dụng của mình hoạt động khi giải quyết không thành công? – Stewie
Hành vi tốt nhất sẽ là chuyển hướng người dùng đến một tuyến đường khác (/ requestError?) Khi giải quyết không thành công. Hoặc/warrantyResult có thể được hiển thị và bộ điều khiển của tuyến đường này sẽ chịu trách nhiệm kiểm tra xem yêu cầu có thành công hay không. – pdegand59