请参阅下面我的 Angular 应用程序的结构:
我有一个名为“firm.html”的页面,其中包含一个按钮。单击此按钮将执行下面的代码。
Controller
Controller 调用服务函数。 GenerationInProgress 变量在 ng-show 中用于切换 HTML 页面上加载 gif 的可见性
$scope.generationInProgress = true;
firmService.processFirm(firmRequest).then(function(response) {
window.location.href = "firm/process";
$scope.generationInProgress = false;
});
公司服务
这是一个通过上面调用的以下函数处理公司操作的服务
this.processFirm = function(firmRequest) {
return httpService.put('firm/process', firmRequest);
};
HTTP 服务
这是一个处理所有对该服务的调用的服务。它被多个服务使用,包括上面的firmService。这是上面调用的 put
方法
this.put = function(url, data) {
return promise = $http.post(url, data).success(function(response) {
return response;
}).error(function(response) {
console.log("error");
});
};
如果服务器返回 HTTP 错误代码,显然会执行 .error
函数。如果我有一个专用的错误页面,我可以重定向到该页面。
但是,我需要在“firm.html”页面上显示错误,同时将 $scope. GenerationInProgress
设置回 false,以便不再显示加载 gif。执行此操作的任何代码都不能位于 httpService 中,因为它是许多不同组件使用的公共(public)服务。
我不确定如何将错误传播回 Controller 以实现此目的。我是否只需将 return response;
放入 .success
和 .error
中,并在 Controller 中使用 IF 语句来测试 HTTP 代码?有其他方法吗?
如有任何建议,我们将不胜感激。
最佳答案
.success
和 .error
方法已被弃用。相反,请使用 .then
和 .catch
方法。
要链接成功的 Promise,请将数据返回
到 .then
方法。要链接被拒绝的 Promise,请抛出
错误响应:
this.put = function(url, data) {
//Use .then method
return promise = $http.post(url, data).then(function(response) {
//return to chain success
return response;
//Use .catch method
}).catch(function(response) {
console.log("error");
//throw to chain rejection
throw response;
});
};
来自文档 1 :
Deprecation Notice
The
$http
legacy promise methods.success
and.error
have been deprecated. Use the standard.then
method instead.
关于javascript - 如何将错误处理与 Controller 和服务集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40025286/