在http拦截器服务中使用$ window

时间:2017-07-08 20:38:35

标签: angularjs ecmascript-6

我试图在http拦截器中使用$ window对象,所以我可以引用localStorage。

问题在于,每当我删除以下行时,我的网络应用程序都能正常运行。但是当我添加它时,没有页面加载,只是一个白色的屏幕,但也没有错误。

let {$window} = this;

我的主要模块配置

$httpProvider.interceptors.push('authInterceptor');

我的 authInterceptor 服务类:

export class authInterceptor {
  constructor($window) {
    this.$window = $window;
  }

  request(config) {
    let {$window} = this;

    return config;
  }

  responseError(response) {
    return response;
  }

}
authInterceptor.$inject = ['$window'];

1 个答案:

答案 0 :(得分:2)

考虑到浏览器支持ES6(并且它受支持,因为拦截器服务是可能被转换的类),let {$window} = this可能导致问题的唯一可能性是this不是不是类实例,甚至是对象。

拦截器函数是用作回调和pushed to the stack的函数。这意味着this将在其中以严格模式undefined

与任何其他用作回调的类方法一样,这些方法应绑定到适当的上下文,以保持它并能够使用注入的服务:

  constructor($window) {
    this.$window = $window;
    this.request = this.request.bind(this);
    this.responseError = this.responseError.bind(this);
  }
相关问题