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() {

  getUser() {
    .subscribe(User => {
      this.userName =;
      this.userId =;

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<any>(``, { 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
            user.authdata = window.btoa(email + ':' + password);
            localStorage.setItem('currentUser', JSON.stringify(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>("", 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.