服务在异常处理程序中变为未定义

时间:2018-11-01 20:08:04

标签: angular angular6 servicestack

我有一项服务可以注入我的UAbilitySystemComponent::AbilityFailedCallbacks。在此服务中,我启动了第三方打字稿客户端,并在服务内部注册了一个方法作为异常处理程序。

我的问题是,当异常处理程序被调用时,AuthenticationService变得不确定。我在构造函数中设置了断点,可以看到AuthenticationService变量已正确填充。但是,当异常处理程序被调用时,它是不确定的。我尝试将其设置为属性,但是会发生相同的行为。

这是我的服务

_auth

我认为这是某种范围的问题,但是我不确定发生了什么。为什么在调用@Injectable({ providedIn: 'root' }) export class DomainAlertsService { client : JsonServiceClient; constructor( private _auth: AuthenticationService ) { this.client = new JsonServiceClient(environment.apiUrl); this.client.exceptionFilter = this.exceptionHandler; } exceptionHandler(ex : Response) { if(ex.status == 401) { this._auth.logout(); // _auth is now undefined location.reload(true); } else{ console.log("unhandled exception"); console.log(ex); } } //.. other methods removed } 方法时未定义_auth

1 个答案:

答案 0 :(得分:4)

我认为您需要将其绑定到组件的范围,就像这样:

this.client.exceptionFilter = this.exceptionHandler.bind(this);