我正在尝试按照此tutorial在Angular中构建一个简单的用户身份验证应用程序。当用户注销后尝试将User对象设置为null时,我遇到错误。
错误:
ERROR in src/app/_services/authentication.service.ts(40,38): error TS2345: Argument of type 'null' is not assignable to parameter of type 'User'.
相关代码(authentication.service.ts):
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {User} from '@/_models';
import { environment } from 'environments/environment';
@Injectable({providedIn: 'root'})
export class AuthenticationService{
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient){
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser') || '{}'));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User{
return this.currentUserSubject.value;
}
login(username: string, password: string){
return this.http.post<any>(`${environment.apiUrl}/user/login/`, {username, password})
.pipe(map(user => {
console.log(user);
// login successful if there is a jwt token in the response
if(user.status && user.data.token){
// store user details and jwt token in local storage to keep user logged in
// between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
}));
}
logout(){
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
我可以通过在tsconfig.json中设置"strict": false
来解决问题,但是我想遵循最佳实践。知道为什么会这样以及如何解决吗?
更新: 用户模型为:
export class User {
id!: number;
username!: string;
token?: string;
}
答案 0 :(得分:0)
问题出在这一行:
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser') || '{}')
在构造函数上,您正在设置currentUserSubject
的值,但是如果currentUser
中没有localStorage
的值,则它将以null
的值启动。
更新
logout(){
localStorage.clear();
this.currentUserSubject = new BehaviorSubject<User>({});
}
答案 1 :(得分:0)
只是一个建议,让我们尝试一下,
logout(){
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject = new BehaviorSubject<User>();
}
new关键字用于初始化对象。因此,将初始化空对象。