在控制台中的ts文件中,记录this.loggedIn,当我输入正确的用户名和密码时,访问令牌存储在本地存储中,并在控制台中首先打印false值,然后在2秒钟后打印true控制台。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
checkStatus = new BehaviorSubject<boolean>(false);
isUserLoggedIn = this.checkStatus.asObservable();
readonly loginUrl= 'http://********';
constructor(private http: HttpClient) { }
checkLogin() {
const access_token = localStorage.getItem('access_token');
if(access_token)
{
this.checkStatus.next(true);
} else {
this.checkStatus.next(false);
}
}
loginUser(user: any) {
return this.http.post(this.loginUrl, user)
.subscribe((success1: any) => {
if(success1) {
localStorage.setItem('access_token', success1.success.token);
// localStorage.setItem('user', JSON.stringify(success.success.token));
return true;
}
});
}
}
这是我的提示:
this.api.loginUser(user);
this.api.isUserLoggedIn.subscribe( (val) => {
// this.loggedIn = val.valueOf();
this.loggedIn = val;
console.log(this.loggedIn);
this.route.navigate(['/dashboard']);
});
答案 0 :(得分:0)
它首先返回false,因为当时用户未登录,val
返回false,但是当用户登录时,将发出新值,这是正确的。试试这个。
loginUser(user: any) {
return this.http.post(this.loginUrl, user);
}
当用户登录时
this.api.loginUser(user).subscribe( () => {
this.api.isUserLoggedIn.subscribe( (val) => {
localStorage.setItem('access_token', success1.success.token);
this.loggedIn = val;
console.log(this.loggedIn);
this.route.navigate(['/dashboard']);
});
});