我有一个单独的功能,例如提交、更新、删除。对于所有功能
$http[method](url)
.then(function(response) {
$scope.successMessage = true;
} , function(response) {
$scope.errorMessageWrong=true;
});
html
<p ng-show="successMessage">Success</p>
<p ng-show="errorMessageWrong"> Something went wrong </p>
用于单独的功能。我需要显示相应的消息。但我不想重复更新、删除和提交的代码,甚至不想重复执行相同操作的其他页面的代码。
如何创建名为 errorHandler 或其他名称的函数。这样我就可以重复使用它。
谁能帮助我
最佳答案
how to create function called
errorHandler
or something. so that i can reuse it.
通过返回已完成的数据响应并抛出拒绝的错误响应来创建可链接 promise 。
下面的示例函数采用 httpPromise 作为参数,将成功或错误消息放在 $scope 上,并返回适合链接的 Promise。
function errorHandler(httpPromise) {
var derivedPromise = httpPromise
.then(function onFulfilled(response) {
$scope.successMessage = true;
//return response for chaining
return response;
},
function onRejected(errorResponse) {
$scope.errorMessageWrong = true;
//throw error to chain rejection
throw errorResponse;
});
//return derivedPromise for chaining
return derivedResponse;
};
然后在客户端代码中:
var httpPromise = $http[method](url);
errorHandler(httpPromise).then( function (response) {
//use data
});
客户端代码保存来自 $http
服务调用的 httpPromise,使用 errorHandler
函数处理 Promise,并使用 返回的派生 Promise errorHandler
函数。
由于调用 Promise 的 then
方法会返回一个新的派生 Promise,因此可以轻松创建 Promise 链。可以创建任意长度的链,并且由于一个 Promise 可以用另一个 Promise 来解决(这将进一步推迟其解决),因此可以在链中的任何点暂停/推迟 Promise 的解决。这使得实现强大的 API 成为可能。 1
关于javascript - 如何在 Angular js中编写服务器错误和成功的全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128782/