Observable implementation in Angular 6

Gabriel Costin

I have been struggling understanding the Angular Observables but I can get it working.I am trying to get data to my dynamic navigation bar and I succeeded in verifying if user is logged in or not and so showing the Login or Logout button but I can't get user data.Below is my implementation

This is user interface:

 interface User{
 status:boolean,
 username:string,
 email:string
 }

User service:

export class UserService {

private Userr :BehaviorSubject<User>

 constructor(private http:HttpClient) { 
this.Userr = new BehaviorSubject<User>({
  status:false,
  username:"",
  email:""  
});
}
setUser(user:User){
this.Userr.next(user);
 }
 get getUserData(){
  return this.Userr.asObservable();
}
 get retrieveData(){
return this.http.get<User>('/api/userdata')
}
}

Below is my navbar ts component implementation:

export class NavbarComponent implements OnInit {

isLoggedIn$: Observable<boolean>;        
 User$ : Observable<User>;
 constructor(private authService: AuthService,private router:Router,private 
 user:UserService) { }

 ngOnInit() {
 this.isLoggedIn$ = this.authService.getLoggedIn; 
 this.User$ = this.user.getUserData;
 }
 }

I didn't post the logout function to only focus about geting data. And in navbar html componenet I have to following:

<a class="nav-link" (click)="logout()" routerLink='/welcome'>Welcome 
{{User$.username}}!,Log Out!</a>

And the error is that User$.username is undefined.Thanks

Edit For anyone who face this problem the solution is to get the username as follows:

{{(User$ | async).username}}!
bgraham

Yep, because the User$ is an observable. So it hasn't returned yet. There are two choices:

1) {{ (User$ | async).username }} which is an Angular syntax to wait for the observable

2)

export class NavbarComponent implements OnInit {

isLoggedIn$: Observable<boolean>;        
 User$ : Observable<User>;
 user: User = {};
 constructor(private authService: AuthService,private router:Router,private 
 user:UserService) { }

 ngOnInit() {
 this.isLoggedIn$ = this.authService.getLoggedIn; 
 this.User$ = this.user.getUserData.subscribe(user => this.user = user);
 }
 }

{{user.username}}

You can wait for the observable in a subscribe method and assign it to a user variable. When it returns, Angular will update the dom with the value of the username.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related