2015-10-29 2 views
1

Я пытаюсь создать простой HTTP-перехватчик в Angular 1.4.x (с ES6 и Babel). Единственное, что ему нужно сделать, это перенаправить на страницу с ошибкой, если обнаружен HTTP 500. Код:Неизвестная ошибка поставщика при использовании ES6

приложение/промежуточный слой/securityInterceptor.service.js

export default class SecurityInterceptorService { 

    constructor($q, $location, config) { 
    'ngInject'; 

    this.$location = $location; 
    this.config = config; 
    this.$q = $q; 
    } 

    responseError(rejection) { 
    var deferred = this.$q.defer(); 

    if (rejection.status === 500) { 
     this.$location.path(this.config.errorPagePath); 
    } 

    deferred.reject(rejection); 
    return deferred.promise; 
    } 
} 

Теперь я получаю неизвестную ошибку провайдера при попытке запустить приложение, говоря, что SecurityInterceptorService неизвестно. Поэтому я посмотрел, как он зарегистрирован. Тем не менее, я не вижу каких-либо очевидных ошибок:

index.module.js

import interceptorConfig from './index.interceptors'; 

import SecurityInterceptorService from '../app/middleware/securityInterceptor.service'; 
// other imports 

angular.module('app', ['ngTouch' /*, other dependencies */]) 
    .config(interceptorConfig) 
    .service('securityInterceptorService', SecurityInterceptorService) 
    // other declarations 

index.interceptors.js

export default function interceptorConfig($httpProvider, securityInterceptorService) { 
    'ngInject'; 

    // Security interceptor 
    $httpProvider.interceptors.push(securityInterceptorService); 
} 

Я могу войти в interceptorConfig функцию, если устраняя зависимость securityInterceptorService. Так что, похоже, услуга не зарегистрирована. Проверял все пути к файлам, проверял наличие орфографических ошибок в именах переменных и т. Д.

Буду признателен, если кто-то сможет указать на ошибку, которую я совершил.

------------------------ Обновление

Следующая функция, которая вводится через .config() работает, однако. Тем не менее, когда я пытаюсь нажать securityInterceptor в этой функции, я получаю ту же неизвестную ошибку поставщика.

export default function config($logProvider, $locationProvider, toastr, $compileProvider) { 
    'ngInject'; 

    // Enable log 
    $logProvider.debugEnabled(true); 

    // Set options third-party lib 
    toastr.options.timeOut = 3000; 
    toastr.options.positionClass = 'toast-top-right'; 
    toastr.options.preventDuplicates = true; 
    toastr.options.progressBar = true; 

    // HTML 5 Modus Enabled No # 
    $locationProvider.html5Mode({ 
    enabled: true, 
    requireBase: false, 
    hashPrefix: '!' 
    }); 

    // Disable debug info 
    $compileProvider.debugInfoEnabled(true); 
} 
+1

'функция interceptorConfig ($ httpProvider, securityInterceptorService)' -> 'securityInterceptorService' не является поставщиком, не так ли? – zeroflagL

+0

@zeroflagL Это не поставщик. –

+0

Вот что я сказал, и в этом проблема. Вы можете вводить провайдеров только в конфигурационную функцию. – zeroflagL

ответ

1

Оказывается, вы не можете вводить услуги в .config(). Это все прекрасно работает при изменении index.interceptors.js на это:

export default function interceptorConfig($httpProvider) { 
    'ngInject'; 

    // Security interceptor 
    $httpProvider.interceptors.push('securityInterceptorService'); 
} 
Смежные вопросы