我试图完成的是查看用户会话是否已经存在,如果已经存在,请将他们登录。但我在如何正确执行这一任务方面遇到了问题。这很可能与代码执行顺序有关,但我不知道该怎么解决。也许是异步?
获取:
TypeError:无法读取未定义的属性"subscribe">
Sidebar.component.ts:
ngOnInit(): void {
this.authService.isLoggedIn.subscribe(res => {
if (res){
this.isLoggedIn = true;
} else {
this.isLoggedIn = false;
}
});
}
auth.service.ts:
get isLoggedIn(): Observable<boolean> {
const authToken = this.cookieService.get('cookiehere');
// console.log(authToken);
if (authToken) {
this.getUserBySession(authToken).subscribe(res => {
console.log(res);
return of(true);
}, error => {
return of(false);
});
}
if (!authToken){
console.log('No token found!');
return of(false);
}
}
getUserBySession(session) {
return this.http.get(`${this.apiPrefix}/auth/get_user_by_session?session=${session}`, { headers: this.headers })
.pipe(map((res: any) => {
if (res.user) {
this.currentUser = res.user;
return res;
} else {
return res;
}}));
}
您在这里订阅了一个可观察项,但没有从getter返回可观察项。那里的return of(true)
从subscribe
回调内部返回,而不是getter。您必须更改它才能从getUserBySession
函数返回原始可观测值
get isLoggedIn(): Observable<boolean> {
const authToken = this.cookieService.get('vmkr');
if (authToken) {
return this.getUserBySession(authToken).pipe(
map(() => true),
catchError(() => of(false))
);
} else {
console.log('No token found!');
return of(false);
}
}
尽管我认为这里的getter可能会在以后的某个地方引发多个订阅的问题。