在我的 Angular-13 專案中,我有這個模型界面:
export interface IUser {
email: string;
token: string;
}
還有這項服務:
export class AccountService {
baseUrl = environment.apiUrl;
private currentUserSource = new ReplaySubject<IUser>(1);
currentUser$ = this.currentUserSource.asObservable();
constructor(private http: HttpClient, private router: Router) { }
loadCurrentUser(token: string) {
if (token === null) {
this.currentUserSource.next(null);
return of(null);
}
let headers = new HttpHeaders();
headers = headers.set('Authorization', `bearer ${token}`);
return this.http.get(this.baseUrl 'account', {headers}).pipe(
map((user: IUser) => {
if (user) {
localStorage.setItem('token', user.token);
this.currentUserSource.next(user);
}
})
);
}
}
但是,我收到了這個錯誤:
null 型別的引數不能分配給 IUser 型別的引數
和 null 突出顯示在:
this.currentUserSource.next(null);
我如何得到這個決心?
謝謝
uj5u.com熱心網友回復:
ReplaySubject.next()預計會收到帶T值的引數。
下一個(值:T):無效
引數
值型別:T。
回傳無效
這T是IUser基于以下宣告:
private currentUserSource = new ReplaySubject<IUser>(1);
解決方案
您可以通過宣告currentUserSource為ReplaySubject<IUser | null>型別來解決它。
private currentUserSource = new ReplaySubject<IUser | null>(1);
StackBlitz 上的示例演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392341.html
