Yun*_*123 1 javascript jquery settimeout angular
我有一个看起来像这样的超时功能:
setTimeout(this.logout, 1000);
Run Code Online (Sandbox Code Playgroud)
登录方式:
logout() {
this.auth_token = "";
this.loggedIn = false;
this.emitLogedInStatusChange();
}
isLoggedIn() {
return this.loggedIn;
}
private emitLogedInStatusChange() {
this.LoggedInStatusChangedEmitter.emit({value: this.loggedIn});
}
Run Code Online (Sandbox Code Playgroud)
其中事件发射器告诉主组件其中loggedIn的值在哪里更改.问题是这个..emitLogedInStatusChange(); 我收到错误信息:
this.emitLogedInStatusChange is not a function
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在注销中正确调用此函数,以便setTimeout可以工作?
这就是我所说的:
map((res) => {
if (res.username === username) {
this.auth_token = res.access_token;
this.sessionId = res.SessionID;
this.loggedIn = true;
this.expires = res.expires_in;
setTimeout(this.logout, this.expires*1000);
this.emitLogedInStatusChange();
}
Run Code Online (Sandbox Code Playgroud)
在传递函数和方法时,始终需要注意如何影响范围this.默认情况下,JS使用调用者的范围.
有一些方法可以明确指定要使用的范围:
setTimeout(this.logout.bind(this), 1000);
Run Code Online (Sandbox Code Playgroud)
但我无法确定,因为您的代码没有显示调用代码的位置.
另外
setTimeout(() => this.logout(), 1000);
Run Code Online (Sandbox Code Playgroud)
可以使用,但似乎不那么简洁.对于将参数传递给回调的其他用例,需要重复使用
someFunction((a, b, c) => this.logout(a, b, c), 1000);
Run Code Online (Sandbox Code Playgroud)