错误:'string 类型的参数 | null' 不能分配给类型为 'string' 的参数。类型 'null' 不可分配给类型 'string'.ts(2345)
错误行:this.setSession(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token'));>
constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { }
login(email: string, password: string) {
return this.webService.login(email, password).pipe(
shareReplay(),
tap((res: HttpResponse<any>) => {
// auth tokens will be in the header of this response
this.setSession(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token'));
console.log('logged in');
console.log(res);
})
)
}
logout() {
this.removeSession();
}
private setSession(userId: string, accessToken: string, refreshToken: string) {
localStorage.setItem('user-id', userId);
localStorage.setItem('access-token', accessToken);
localStorage.setItem('refresh-token', refreshToken);
}
private removeSession() {
localStorage.removeItem('user-id');
localStorage.removeItem('access-token');
localStorage.removeItem('refresh-token');
}
}```
答案 0 :(得分:1)
看起来参数 res.body._id
、res.headers.get('x-access-token')
、res.headers.get('x-refresh-token')
中的一个具有空值并且您将它们的类型定义为字符串。
-尝试 console.log(res.body._id, res.headers.get('x-access-token'), res.headers.get('x-refresh-token')) 看看是哪一个返回空值。
-尝试更改声明
private setSession(userId: string, accessToken: string, refreshToken: string)
到 private setSession(userId: string|null, accessToken: string|null, refreshToken: string|null)