我正在尝试为我的AngularJS应用程序编写HTTP拦截器来处理身份验证.
这段代码有效,但我担心手动注入服务,因为我认为Angular应该自动处理:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($location, $injector) {
return {
'request': function (config) {
//injected manually to get around circular dependency problem.
var AuthService = $injector.get('AuthService');
console.log(AuthService);
console.log('in request interceptor');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user is not logged in.');
$location.path('/login');
}
return config;
}
};
})
}]);
Run Code Online (Sandbox Code Playgroud)
我开始做的事情,但遇到循环依赖问题:
app.config(function ($provide, $httpProvider) {
$provide.factory('HttpInterceptor', function ($q, $location, AuthService) {
return {
'request': function (config) {
console.log('in request interceptor.');
if (!AuthService.isAuthenticated() && $location.path != '/login') {
console.log('user …Run Code Online (Sandbox Code Playgroud) 嗨,我已成功使用OOP与AngularJs一段时间了(首先使用带有oop继承的angularjs开始 ),提供的方法允许您将类定义为角度服务,稍后您可以扩展或继承这样的类:
Application.factory('AbstractObject', [function () {
var AbstractObject = Class.extend({
virtualMethod: function() {
alert("Hello world");
},
abstractMethod: function() { // You may omit abstract definitions, but they make your interface more readable
throw new Error("Pure abstract call");
}
});
return AbstractObject; // You return class definition instead of it's instance
}]);
Application.factory('DerivedObject', ['AbstractObject', function (AbstractObject) {
var DerivedObject = AbstractObject.extend({
virtualMethod: function() { // Shows two alerts: `Hey!` and `Hello world`
alert("Hey!");
this._super();
},
abstractMethod: …Run Code Online (Sandbox Code Playgroud)