简体   繁体   中英

await dataService between components Angular, Behavior Subject

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM