Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using `$mdToast` inside an interceptor triggering circular dependency

Question:

How can I use $mdToast inside an interceptor without triggering the error?

Setup:

Interceptor definition:

(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;
  }
})();

Interceptor config:

(function () {
  'use strict';

  angular
    .module('app.components.http-errors-interceptors')
    .config(moduleConfig);

  /* @ngInject */
  function moduleConfig($httpProvider) {
    $httpProvider.interceptors.push('HttpError500Interceptor');
  }
})();

Issue:

When I load the application it triggers the following error:

Uncaught Error: [$injector:cdep] Circular dependency found: $http <- $templateRequest <- $$animateQueue <- $animate <- $$interimElement <- $mdToast <- HttpError500Interceptor <- $http <- $templateFactory <- $view <- $state

like image 632
Diosney Avatar asked Jan 31 '16 20:01

Diosney


1 Answers

One work around that has helped me in the past is to use $injector to get your dependency at runtime instead of at configuration time. So, something like:

  /* @ngInject */
  function HttpError500Interceptor($q,
                                   $injector,
                                   $filter) {
    function responseError(responseError) {
      var $mdToast = $injector.get('$mdToast');

When your cyclic dependency does not cause problems, which it probably doesn't in this case, this will do the trick.

like image 171
Lodewijk Bogaards Avatar answered Nov 15 '22 03:11

Lodewijk Bogaards