【问题标题】:Angular Typescript dependency injection explicit annotation error in strict mode严格模式下的Angular Typescript依赖注入显式注释错误
【发布时间】:2017-02-09 03:06:30
【问题描述】:

我正在使用带有 typescript 的 angular 1.5,我想创建一个拦截器以在自定义标头中插入令牌并从每个响应中更新它。

运行时出现以下异常:

未捕获的错误:[$injector:strictdi] 函数($q) 未使用 显式注解,不能在严格模式下调用

class AuthInterceptor implements ng.IHttpInterceptor {

  $q:ng.IQService;

  static $inject = ['$q'];
  constructor($q:ng.IQService) {
    this.$q = $q;
  }

  static factory($q:ng.IQService):AuthInterceptor {
    return new AuthInterceptor($q);
  }


  request = (config:ng.IRequestConfig):ng.IRequestConfig => {
   // config.headers = config.headers || {};
   console.info('Request config md', config);
   // config.headers['token'] = 'test token';

   return config;
 };

  response = <T>(response: ng.IHttpPromiseCallbackArg<T>):ng.IPromise<T> => {
    console.info('Response:', response);

// modify response

  return this.$q.when(response);
};

}

let httpConfig = ($httpProvider:ng.IHttpProvider) => {
   $httpProvider.interceptors.push(AuthInterceptor.factory);
};

angular.module('app').config(httpConfig);

你有什么想法,我该如何解决这个问题?

提前致谢。

【问题讨论】:

    标签: angularjs typescript dependency-injection annotations


    【解决方案1】:

    请试试这个。这是每个请求的最简单的拦截器

    app.factory('myInterceptor', function() {  
            var requestInterceptor = {
                request: function(config) {
                    return config;
                }
            };
            return requestInterceptor;
        });
    
        app.config(['$httpProvider', function($httpProvider) {  
            $httpProvider.interceptors.push('myInterceptor');
        }]);
    

    【讨论】:

    • 感谢您的回复。但是,我需要 $q 来拦截响应。我也需要使用打字稿。
    • @Jhankar 你也可以在那里使用 $q
    • 如果我使用 $q 作为依赖注入,由于使用严格模式,我会收到上述错误。
    • @Jhankar 参考此链接。你会明白的。 [stackoverflow.com/questions/19770889/…
    猜你喜欢
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2020-02-13
    • 2016-07-19
    相关资源
    最近更新 更多