我正在玩弄 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);
有什么问题?