ฉันกำลังพยายามเขียนตัวดักจับ HTTP สำหรับแอป AngularJS เพื่อจัดการการตรวจสอบสิทธิ์
รหัสนี้ใช้งานได้ แต่ฉันกังวลเกี่ยวกับการฉีดบริการด้วยตนเองเนื่องจากฉันคิดว่า 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;
}
};
})
}]);
สิ่งที่ฉันเริ่มทำ แต่พบปัญหาการพึ่งพาแบบวงกลม:
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');
});
อีกเหตุผลหนึ่งที่ฉันกังวลคือส่วนของ $ httpใน Angular Docs ดูเหมือนจะแสดงวิธีรับการอ้างอิงที่ฉีด "วิธีปกติ" ลงในตัวดักจับ Http ดูข้อมูลโค้ดใต้ "Interceptors":
// 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');
โค้ดด้านบนควรไปที่ไหน
ฉันเดาว่าคำถามของฉันคือวิธีที่ถูกต้องในการทำสิ่งนี้คืออะไร?
ขอบคุณและฉันหวังว่าคำถามของฉันจะชัดเจนเพียงพอ
$http
ในบางสถานการณ์เพื่อให้มีการพึ่งพาวงกลมแม้สั้นบน วิธีเดียวที่ฉันพบคือใช้$injector.get
แต่จะเป็นการดีที่จะทราบว่ามีวิธีที่ดีในการจัดโครงสร้างโค้ดเพื่อหลีกเลี่ยงปัญหานี้หรือไม่