【发布时间】:2021-05-12 12:51:38
【问题描述】:
我是 Angular/Node.js 的初学者,我正在做一个项目作为练习。 我在使用订阅和可观察对象时遇到了身份验证问题。
虽然我的身份验证有效,但我试图在成功的身份验证时隐藏我的登录/注册按钮,并改为显示一个注销按钮。
我使用 '*ngIf="userIsAuthenticated"' 来显示我的注销并使用 '*ngIf="!userIsAuthenticated"' 来隐藏注册/登录按钮。
在我的 authService 类文件中,我有这个:
private authStatusListener = new Subject<boolean>();
constructor(private http: HttpClient, private router: Router) {}
getAuthStatusListener() {
return this.authStatusListener.asObservable();}
login(email: string, nickname: null, password: string ) {
const authData: AuthData = {
email: email,
nickname: nickname,
password: password,
};
this.http
.post<{token: string}>(BACKEND_URL + '/login', authData)
.subscribe((response) => {
const token = response.token;
this.token = token;
this.authStatusListener.next(true);
this.router.navigate(["/"]);
});}
在我的组件 .ts 文件中,我有这个:
private authListenerSubs: Subscription;
userIsAuthenticated = false;
constructor(
private authService: AuthService,
public reviewService: ReviewService)
ngOnInit() {
this.authListenerSubs = this.authService
.getAuthStatusListener()
.subscribe((isAuthenticated) => {
console.log('testing if this runs');
console.log(this.userIsAuthenticated);
this.userIsAuthenticated = isAuthenticated;
console.log(this.userIsAuthenticated);
});
console.log(this.userIsAuthenticated);
this.authListenerSubs = this.authService
.getAuthStatusListener()
.subscribe();}
我放了一堆 console.logs 来查看我的变量的行为。您也可能注意到看似无用的代码this.authListenerSubs = this.authService .getAuthStatusListener() .subscribe();
但是如果这段代码不在该代码之下,我在订阅方法中的任何日志都不会由于某种原因而执行,我不知道为什么会这样或者这些事情是如何相关的。
主要问题是 this.userIsAuthenticated 不会被更新。 我的日志说该值应该从 false 开始,然后按应该的方式更改为 true,但是当它完成订阅时,它会立即返回 false 值,即使它不应该因为它被更改并且我无法将其改回 false。
谁能帮帮我?
【问题讨论】:
-
我注意到
login方法没有在任何地方调用。它与问题相关吗?
标签: angular typescript observable subscription subscribe