我在玩的代码http://ngmodules.org/modules/http-auth-interceptor我想知道为什么
$rootScope.$broadcast('loginRequired');
不会触发控制器中的警报
$scope.$on('loginRequired',function() {
alert('loginRequired');
});
代码:
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" class="ng-view"></div>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script>
var buffer = angular.module('http-auth-interceptor-buffer', []);
buffer.factory('httpBuffer', function($injector) {
var buffer = [];
var $http;
function retryHttpRequest(config, deferred) {
function successCallback(response) {
deferred.resolve(response);
}
function errorCallback(response) {
deferred.reject(response);
}
$http = $http || $injector.get('$http');
$http(config).then(successCallback, errorCallback);
}
return {
append: function(config, deferred) {
buffer.push({
config: config,
deferred: deferred
});
},
retryAll: function(updater) {
for (var i = 0; i < buffer.length; ++i) {
retryHttpRequest(updater(buffer[i].config), buffer[i].deferred);
}
buffer = [];
}
};
});
var app = angular.module('myModule', ['http-auth-interceptor-buffer']);
app.config(function($httpProvider,$routeProvider, $locationProvider) {
$httpProvider.interceptors.push('securityInterceptor');
$routeProvider.
when('/one',{
controller: 'OneCtrl',
/*resolve: {
my: function(Data) {
return Data.getData();
}
},*/
templateUrl: './_one.html'
}).
when('/two', {
controller: 'TwoCtrl',
templateUrl:'./_two.html'
})
.otherwise({
redirectTo: '/one'
});
});
app.controller('OneCtrl',function($scope,Data) {
$scope.my = Data.getData();
$scope.$on('loginRequired',function() {
alert('loginRequired');
});
});
app.controller('TwoCtrl',function($scope) {
});
app.factory('Data', function($http,$q) {
return {
getData : function() {
var deferred = $q.defer();
var promise = $http.get('./security.php').success(function (response) {
deferred.resolve(response);
});
// Return the promise to the controller
return deferred.promise;
}
}
});
app.factory('securityInterceptor', function($q, $rootScope,httpBuffer) {
return {
request: function(config) {
return config || $q.when(config);
},
requestError: function(rejection) {
},
response: function(response) {
return response || $q.when(response);
},
responseError: function(rejection) {
if(rejection.status === 401) {
var deferred = $q.defer();
httpBuffer.append(rejection.config, deferred);
$rootScope.$broadcast('loginRequired');
return deferred.promise;
}
return $q.reject(rejection);
}
};
});
</script>
</body>
</html>
更新
安全性.php
<?php
header('HTTP/1.1 401 Unauthorized');
$data = 'MyTets';
echo json_encode($data);
有什么麻烦?
我通过放置来测试您的代码
$rootScope.$broadcast('loginRequired');
在安全拦截器
response: function(response) {
$rootScope.$broadcast('loginRequired');
return response || $q.when(response);
},
模拟 PHP 文件的响应时出现问题。您的代码和事件运行良好。它应该来自您的 php 文件,该文件没有返回 401,对吗?
这里有一个 plunker