我在 Angular 应用程序中使用 ngx-cookie-service 模块来临时存储用户相关信息,例如“用户名”或“用户 ID”。对于第一个尝试登录该应用程序的用户,该应用程序运行良好。它从 cookie 中获取正确的用户名、userId 等信息。然而,当其他用户随后尝试登录时,尽管新用户的信息看起来像存储在 cookie 中,但 http 请求仍然使用前一个用户的信息进行。如果我尝试获取如下所示的 userId 信息,则会出现问题。
export class ImageService {
constructor(private http: HttpClient, private cookieService: CookieService) {
}
userId: number = +this.cookieService.get('user_id');
getImage(): Observable<Image> {
return this.http.get<Image>(imageUrlExample + this.userId);
}
}
但是,如果我从方法内的cookie获取userId信息,则不会出现该问题。
export class ImageService {
constructor(private http: HttpClient, private cookieService: CookieService) {
}
getImage(): Observable<Image> {
const userId: number = +this.cookieService.get('user_id');
return this.http.get<Image>(imageUrlExample + userId);
}
}
我认为这个问题可能是由于缓存index.html文件而发生的,但不知道如何在Angular中清除缓存。
顺便说一句,我使用 NGINX 作为 Web 服务器。如果有它的配置,不幸的是我找不到它。
我尝试清除缓存index.html 文件,但无法清除它,或者由于其他原因而发生问题。我还尝试配置 NGINX 进行缓存,但也没有成功。
我认为您拥有使用户脱离实际功能的代码,因此在加载应用程序时此代码仅执行一次(在初始化服务时)。这很糟糕,因为我们将无法检测其他用户 ID。
您可以轻松地解决此问题,方法是将获取用户 ID 代码放入函数中,以便在调用函数时始终对其进行求值,从而始终获取最新值。
export class ImageService {
constructor(private http: HttpClient, private cookieService: CookieService) {
}
getImage(): Observable<Image> {
const userId: number = +this.cookieService.get('user_id');
return this.http.get<Image>(imageUrlExample + userId);
}
}
替代方法是在需要时使用 getter 来获取最新的 cookie
export class ImageService {
constructor(private http: HttpClient, private cookieService: CookieService) {
}
get userId() { return +this.cookieService.get('user_id'); }
getImage(): Observable<Image> {
return this.http.get<Image>(imageUrlExample + this.userId);
}
}