Reputation: 4572
I have a Behavior Subject dataService in Angular that makes a request to server to get the user details when admin-layout-component loads (parent component), and then injects the data in the user component, this is my user component onInit:
ngOnInit(){
this._dataService.currentUserDetails.subscribe(userDetails => this.userDetails = userDetails);
console.log(this.userDetails);
if(this.userDetails === ''){
this.getUser();
}
}
When i refresh the browser in user component, first loads the current component ngOnInit, i have to make the conditional to check userDetails and make a new request to server, but admin-layout-component is making the request too, my question: There is a way to await the dataService so i don't have to make the getUser() twice?. Thanks in advance.
Upvotes: 0
Views: 43
Reputation: 5415
You can use Subject to store information about user and if you need, you always get data from subject by this.userDetails
anywhere in you component:
export class Component implements OnInit {
userDetails$ = new BehaviorSubject<any>(null);
ngOnInit(){
this._dataService.currentUserDetails.subscribe(userDetails => {
this.userDetails.next(userDetails)
});
}
get userDetails(): any {
return this.userDetails$.getValue();
}
}
and in template you can subscribe to your service Subject
<div> {{ userDetails$ | async }} </div>
Upvotes: 1