【发布时间】:2017-05-12 17:26:05
【问题描述】:
我已经为应用程序全局创建了通知服务,同时发送 db 调用,在拦截器中捕获错误代码并显示警报。
如何避免角度通知服务中出现重复的错误消息。 拦截器代码
var interceptor = function ($q, alerts, $rootScope, $timeout, $location, alertsManager) {
return {
request: function (config) {
console.log(config);
return config;
},
response: function (response) {
var deferred = $q.defer();
//$rootScope.$broadcast('loginRequired');
//$scope.alerts.push({ msg: "Request done !" });
return response || $q.when(response);
},
responseError: function (rejection) {
if (rejection.status == 500)
{
var deferred = $q.defer();
$rootScope.$broadcast('loginRequired');
return $q.reject(rejection);
}
console.log(rejection.status);
return $q.reject(rejection);
}
}
};
$httpProvider.interceptors.push(interceptor);
在控制器内部调用服务器调用响应。
LoginService.AfterLogin(UserName, Password)).then(function (response) {
},function (status) {
if (status === 500) {
alert("200");
$rootScope.$on("loginRequired", function (e) {
alertsManager.addAlert('Technical Error Occurred.Please contact the System Administrator for the further support!!', 'alert-success');
});
}
});
工厂警报服务
App.factory('alertsManager', function () {
return {
alerts: {},
addAlert: function (message, type) {
this.alerts[type] = this.alerts[type] || [];
this.alerts[type].push(message);
},
clearAlerts: function () {
for (var x in this.alerts) {
delete this.alerts[x];
}
}
};
});
方法一:
<div ng-controller="AlertsController">
<div ng-repeat="(key,val) in alerts" class=" alert {{key}}" id="alert-notify">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div ng-repeat="msg in val">{{msg}}</div>
</div>
</div>
方法1: 方法2: 当我通过 $index 使用 track 时,会被重复。
<div ng-controller="AlertsController">
<div ng-repeat="(key,val) in alerts track by $index" class=" alert {{key}}" id="alert-notify">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<div ng-repeat="msg in val track by $index">{{msg}}</div>
</div>
</div>
【问题讨论】:
-
你为什么把它标记为 angular2?
-
最后一个例子不正确吗?您能否展示实际数据,以便我们知道它应该是什么样子?
-
我没听懂你在说什么,触发了 2 次错误响应并显示重复错误。
-
你的拦截器被多次调用导致多个错误消息与
track by无关。 -
您只期待一条错误消息吗?你确定只打了一个电话吗?
标签: angularjs angularjs-directive angularjs-scope angular-ui-router angular-services