Tôi đang cố gắng viết một trình đánh chặn HTTP cho ứng dụng AngularJS của mình để xử lý xác thực.
Mã này hoạt động, nhưng tôi lo ngại về việc tiêm dịch vụ theo cách thủ công vì tôi nghĩ Angular phải tự động xử lý điều này:
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;
}
};
})
}]);
Những gì tôi bắt đầu làm, nhưng gặp phải các vấn đề phụ thuộc vòng tròn:
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 is not logged in.');
$location.path('/login');
}
return config;
}
};
});
$httpProvider.interceptors.push('HttpInterceptor');
});
Một lý do khác khiến tôi lo ngại là phần trên $ http trong Angular Docs dường như chỉ ra một cách để đưa các phần phụ thuộc vào "một cách thông thường" vào bộ đánh chặn Http. Xem đoạn mã của họ trong "Bộ chặn":
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
// optional method
'request': function(config) {
// do something on success
return config || $q.when(config);
},
// optional method
'requestError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
},
// optional method
'response': function(response) {
// do something on success
return response || $q.when(response);
},
// optional method
'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
}
return $q.reject(rejection);
};
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
Đoạn mã trên nên đi đâu?
Tôi đoán câu hỏi của tôi là cách thích hợp để làm điều này là gì?
Cảm ơn, và tôi hy vọng câu hỏi của tôi đủ rõ ràng.
$http
. Cách duy nhất mà tôi tìm thấy là sử dụng $injector.get
, nhưng sẽ thật tuyệt nếu biết liệu có cách tốt nào để cấu trúc mã để tránh điều này.