[英]AngularJS: Injecting service into a HTTP interceptor (Circular dependency)
[英]Using `$mdToast` inside an interceptor triggering circular dependency
題:
如何在攔截器內使用$mdToast
而不觸發錯誤?
建立:
攔截器定義:
(function () {
'use strict';
angular
.module('app.components.http-errors-interceptors')
.factory('HttpError500Interceptor', HttpError500Interceptor);
/* @ngInject */
function HttpError500Interceptor($q,
$mdToast,
$filter) {
var interceptor = {};
interceptor.responseError = responseError;
function responseError(responseError) {
if (responseError.status === 500) {
$mdToast.show($mdToast.simple()
.content($filter('translate')('APP.COMPONENTS.HTTP_ERRORS_INTERCEPTORS.500'))
.position('bottom right')
.hideDelay(5000));
}
return $q.reject(responseError);
}
return interceptor;
}
})();
攔截器配置:
(function () {
'use strict';
angular
.module('app.components.http-errors-interceptors')
.config(moduleConfig);
/* @ngInject */
function moduleConfig($httpProvider) {
$httpProvider.interceptors.push('HttpError500Interceptor');
}
})();
問題:
當我加載應用程序時,它會觸發以下錯誤:
未捕獲錯誤:[$ injector:cdep]找到循環依賴項:$ http < - $ templateRequest < - $$ animateQueue < - $ animate < - $$ interimElement < - $ mdToast < - HttpError500Interceptor < - $ http < - $ templateFactory < - $ view < - $ state
過去幫助我的一個方法就是使用$injector
來在運行時而不是在配置時獲得依賴。 所以,像:
/* @ngInject */
function HttpError500Interceptor($q,
$injector,
$filter) {
function responseError(responseError) {
var $mdToast = $injector.get('$mdToast');
如果你的循環依賴不會導致問題,在這種情況下它可能不會出現問題,這將解決問題。
這兩個提供的解決方案都沒有為我工作,所以我在這里發布了我所做的事情,因此任何有相同問題的人都可以使用各種解決方法。
我真正想要的是擁有一個通用組件來處理名為interceptors
HTTP攔截interceptors
並直接從模塊顯示消息,並且很高興,因為最終的解決方案更優雅,它在注入$mdToast
服務時觸發了這個錯誤。
我后來提到的解決方案,更優雅,我對此問題的第一個解決方案是:
interceptors
HTTP攔截interceptors
, notifications-hub
全局通知。 然后,在interceptors
模塊中,我觸發一個全局事件:
$rootScope.$broadcast('notifications:httpError', responseError);
然后,在notifications-hub
模塊中,我在事件上注冊並使用$mdToast
,它在通知服務中注入時沒有錯誤:
$rootScope.$on('notifications:httpError', function (event, responseError) { NotificationsHubService.processErrorsAndShowToast(responseError); });
NotificationsHubService
是注入$mdToast
的服務。
結論:
我使用全局事件作為低級攔截器和通知子系統之間的粘合劑來克服該問題。
希望它對任何人都有用。
你應該做的是創建一個在運行時為你帶來烤面包機的功能
var getToaster = ()=>{
var toaster = $injector.get('$mdToaster');
return toaster;
}
現在只在你需要時調用它 - 這將提供一個圍繞依賴循環的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.