【发布时间】:2018-12-19 23:18:56
【问题描述】:
以下可观察的:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';
@Injectable()
export class AuthService {
readonly loginUrl = <login_url>;
readonly authStatusUrl = <auth_status_url>;
constructor(private http: HttpClient, private cookieService: CookieService) {}
loggingIn = false;
login(username: string, password: string) {
this.loggingIn = true;
const creds = {
username: username,
password: password
};
this.http
.post<any>(this.loginUrl, creds, {})
.subscribe(
data => this.onLoginSuccess(data),
error => this.onLoginFail(error));
}
handleAuth(): Observable<any> {
const token = this.cookieService.get('token');
const refresh = this.cookieService.get('refresh');
// should wait for loggingIn to be false
return this.http
.post<any>(this.authStatusUrl, { }, {
headers: {
token: token,
refresh: refresh
}
});
}
public onLoginSuccess(data) {
this.loggingIn = false;
this.cookieService.set('token', data.access_token);
this.cookieService.set('refresh', data.refresh_token);
}
onLoginFail(err) {
console.log('Faild to login');
this.loggingIn = false;
}
}
在局部变量为假之前不应执行。
我读到这应该使用 Promises 和带有 await 运算符的异步函数调用来完成,但我找不到可以轮询变量值的东西,只能“等待一段时间并解决”。
主要思想是调用handleAuth,在内部它应该通过等待局部变量(或发生某些事情)来确保登录不在进行中
【问题讨论】:
-
贴出局部变量和代码
-
也许在这个局部变量上使用了setter?
-
添加了整个代码
-
IMO:我会询问如何在令牌过期时刷新令牌,而不是非常广泛地询问您选择的这种技术解决方案。
-
为什么不调用函数handleAuth(),在这里设置this.loggingIn = false;
标签: angular typescript promise observable angular7