2016-01-14 71 views
1

我有一个拦截器,我正在配置以加载ajax微调器。

interface IInterceptorScope extends angular.IRootScopeService { 
     loading: number; 
    } 

    export class Interceptor { 

     public static Factory($q: angular.IQService, $rootScope : IInterceptorScope) { 
      return new Interceptor($q, $rootScope); 
     } 


     constructor(private $q: angular.IQService, private $rootScope: IInterceptorScope) { 
      this.$rootScope.loading = 0; 
     } 


     public response(response) { 
      console.log(response); 
      this.$rootScope.loading = 1; 
      return response || this.$q.when(response); 
     } 

     public responseError(rejection) { 
      console.log(rejection.status); 
      if (rejection.status === 401) { 
      } 

      return this.$q.reject(rejection); 
     } 
    } 

我收到此错误:

enter image description here

$q也没有定义。我不知道为什么。任何人都可以帮忙吗?

编辑:这是我如何加入我的config()块内的拦截器,再减去其他参数,它看起来像这样:

.config($httpProvider : angular.IHttpProvider) => { 
    $httpProvider.interceptors.push(Interceptor.Factory); 
} 

和注册工厂:

.factory('Interceptor', Interceptor) 

作为参考,我在这里看第一个答案:

AngularJS global $http state ajax loader

$rootScope在这里有加载属性,但这是在纯JavaScript中,所以我不知道它是否与TypeScript的方式在这里。

+0

你没有收到responseError里面的错误,因为可能你的代码没有打到该块 – gaurav5430

+0

请说明你如何注册拦截器? – miensol

+0

嗨,我刚刚重新编辑了我的答案。 – Thomas

回答

6

角度调用response方法没有设置this;以打字稿来处理这个问题,使用功能属性来捕捉this,如:

public response = (response) => { 
    console.log(response); 
    this.$rootScope.loading = 1; 
    return response || this.$q.when(response); 
} 

同为responseError为好。

+0

就是这样。非常感谢你!请问这是否仅适用于http拦截器方法,还是在其他情况下会发生? – Thomas

+1

@Thomas - 当你的方法被用作回调时,这很常见,尽管它依赖于调用代码。在Angular中有几个地方会碰到它 - 例如,指令链接函数。 –

+0

非常好,非常感谢,救了我! – Ric