@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}/users/authenticate`, { username, password })
.pipe(map(user => {
// 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);
return user;
}));
}
logout() {
// handle logging out the user
this.removeCurrentUserFromLocalStorageAndBehaviorSubject();
}
private removeCurrentUserFromLocalStorageAndBehaviorSubject() {
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
Can someone help me understand why I am encountering an error on the last line (this.currentUserSubject.next(null))? The error message states: Argument of type 'null' is not assignable to parameter of type 'User'. Is this due to the latest TypeScript version restrictions? What could be an alternative solution?