Angular setting username and ID when I refresh browser

so, I’d expect to see user name of currently logged in when someone logs in but I have to refresh the browser first?! why?

ngOnInit() {
    this.getUser();
  }

  getUser() {
    this.authenticationService.getProfile()
    .pipe(takeUntil(this.destroy$))
    .subscribe(User => {
      this.userName = User.name;
      this.userId = User.id;
    });
  }

So this issue could be related to change detection, if your component is using onPush change detection. Otherwise this isn’t specifically an Angular issue, or at least an issue with the code you have posted.

It could be an issue elsewhere in your stack, or just a straight timing issue, where you get the user’s profile and don’t actually get the information for the current user in User.

Overall debug the data in the network, your back-end, and different parts of the Angular service to find where “user is blank”, and when User is blank. For example, if how you get the user relies on the session data, and the session isn’t set when you get the user, you don’t get the data you expect.

Good luck :+1:

here is my service file:

login(email: string, password: string) {
    return this.http.post<any>(`https://lookwhatfound.me/api/auth/login`, { email, password, withCredentials: true })
        .pipe(map(user => {
            // store user details and basic auth credentials in local storage to keep user logged in between page refreshes
            this.router.navigate(['/]']);
            user.authdata = window.btoa(email + ':' + password);
            localStorage.setItem('currentUser', JSON.stringify(user));
            this.currentUserSubject.next(user);
            return user;
        }));
  }

  getProfile(): Observable<any> {
    const currentUser = localStorage.getItem('currentUser');
    const token = JSON.parse(currentUser).token;
    this.userName = JSON.parse(currentUser).name;
    const httpHeaders = {
      headers: new HttpHeaders({
        'content-type': 'application/json',
        'Authorization': 'Bearer '+token
      })
    }

    return this.http.get<any>("https://lookwhatfound.me/api/auth/profile", httpHeaders)
      .pipe(map(profile => {
        console.log('profile: ',profile)
        return profile;
      }))
  }

maybe username should be set in there somehow?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.