Home > front end >  Display username in the profile section in the navbar
Display username in the profile section in the navbar

Time:02-03

I'm trying to display the username in the navbar. I managed to do it using my profile service like this:

let user of profileService.getProfile(), which uses the subscribe in order to retrieve the data.

However, the first time that I log in the name won't pop out. If I refresh the browser, the name will be displayed. I guess that it has something to do with the subscribe and its asynchronous nature, but if that's the case, what would be the best solution to the problem?

CodePudding user response:

As you mentioned in the comment your getProfile() returns an observable. You can subscribe to it in your component and then display the user name in your HTML component:

userName: string;

constructor(private profileService: ProfileService){}

ngOnInit(): void { 
   this.profileService.getProfile().subscribe((resp)=>{
      //Assuming response only returns username
      this.userName = resp;
   });
}

and then in your HTML you can just bind to userName.

 <div>
    Logged in user name is: {{userName}} 
 </div>

CodePudding user response:

I think that you can create a BehaviorSubject in service, it has a method getValue() that give a current value :

user$ : BehaviorSubject<String> = new BehaviorSubject("");

setProfile() {
    this.user$.next("newName");
}

getProfile(): string {
    return this.user$.getValue();
}

In View, you can use a pipe (AsyncPipe) to subscribe observable like :

{{ userOfProfileService$ | async }}

However, you can also use Subject observable without getProfile() but just with AsyncPipe in view.

    user$ : Subject<String> = new Subject();
  •  Tags:  
  • Related