gpt4 book ai didi

angular - 类型 'null' 的参数不可分配给参数 Angular

转载 作者:行者123 更新时间:2023-12-05 08:47:42 25 4
gpt4 key购买 nike

@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() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}

知道为什么我在最后一行 (this.currentUserSubject.next(null)) 出现错误吗?错误消息:“null”类型的参数不可分配给“User”类型的参数。最新的 typescript 版本不允许这样做吗?另一种解决方案是什么?

最佳答案

Typescript 变得更加严格。

您可以关闭严格模式或让您的可观察对象接受null:

private currentUserSubject: BehaviorSubject<User | null>;

关于angular - 类型 'null' 的参数不可分配给参数 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67025848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com