我们在应用程序中使用 angular-toastr.js。我们在所有编辑表单中使用以下指令:
app.directive('serverError', ['resourceFactory','spinnerService', 'toastr', function (resourceFactory,spinnerService,toastr) {
return {
restrict: 'A',
controller: ['$scope', '$timeout', function ($scope, $timeout) {
var errorToastConfig = {closeButton:true,timeOut:0,tapToDismiss:true};
$scope.$on('sm:badRequest', function (event, data) {
angular.forEach(data, function (value, key) {
if (value.message == '') value.message = 'The ' + value.property + ' value is invalid.'
});
$scope.errors = data;
//$scope.alertMessage = resourceFactory.getResource('Messages', 'errorOnForm');
//$scope.alertType = 'error';
$timeout(function () {
spinnerService.stopSpinner();
}, 0);
toastr.clear();
var errorMsg = ($scope.errors[0] && $scope.errors[0].message?$scope.errors[0].message:resourceFactory.getResource('Messages', 'errorOnForm'));
toastr.error(errorMsg, errorToastConfig);
$scope.disableAction = false;
});
问题是,当页面遇到错误请求时,我在屏幕上看到 3 条 toastr 消息,而不仅仅是 1 条。一条来 self 的 Controller 代码,两条来自该指令,因为该代码由 Angular 执行了两次。添加 toastr.clear() 并不能解决问题。理想情况下,如果 Controller 的代码已经处理了错误,我根本不想运行代码。否则我想确保只显示一个带有错误信息的 toastr。您看出上面需要更改哪些内容了吗?
更新。我还可以展示我们的主要 app.js 代码来处理不良请求。当我调试代码时,我可以看到指令代码触发了两次,并且执行调用时 toastrs 数组为空。
这是应用程序的代码:
app.factory('badRequestInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {
return {
'responseError': function (rejection) {
if (rejection.status === 400) {
$rootScope.$broadcast("sm:badRequest", rejection.data);
}
return $q.reject(rejection);
}
};
}]);
app.factory('noConnectionInterceptor', ['$rootScope', '$q', function ($rootScope, $q) {
return {
'responseError': function (rejection) {
console.dir(rejection);
if (rejection.status === -1) {
$rootScope.$broadcast("sm:noConnection");
}
return $q.reject(rejection);
}
};
}]);
最佳答案
您可以通过将 preventDuplicates
属性设置为 true
来防止出现相同的 Toast 堆栈。
From docs: Duplicates are matched to the previous toast based on their message content.
只需将该属性添加到您的 errorToastConfig
中即可:
var errorToastConfig = {closeButton:true,timeOut:0,tapToDismiss:true, preventDuplicates:true};
参见docs了解更多信息。
关于javascript - 仅显示 1 个 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951687/