Search code examples
htmlangularnginxngx-cookie-service

Cannot get the current user information from the cookies when a new user logs in


I'm using ngx-cookie-service module in my Angular app to store user related information like "username" or "userId" temporarily. For the first user trying to log in to the app, the app works fine. It gets the correct username, userId etc. information from the cookies. However, when a different user tries to log in afterwards, although the new user's info looks like stored in cookies, the http requests are still made with the previous user's information. If I try to get userId information like below the issue occurs.

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);
  }
}

However, if I get the userId information from the cookie inside the method, the issue does not occur.

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);
  }
}

I think the issue might happen because of caching index.html file but do not know how to clear the cache in Angular.

By the way I use NGINX for the web server. If there is a configuration for it unfortunately I couldn't find it exactly.

I tried to clear caching index.html file but I couldn't clear it or the problem happens because of something else. I also tried to configure NGINX for the caching but it wasn't successful as well.


Solution

  • I think you are having the code to get the user outside the actual function, so this code is executed only once (when the service is initialized) when the app is loaded. This is bad since we will not be able to detect other user ids.

    You can easily remedy this, by putting the get user id code inside the function, so that it's always evaluated when the function is called, hence always getting the latest value.

    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);
      }
    }
    

    Alternative is to use a getter to get the latest cookie when needed

    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);
      }
    }