简体   繁体   English

组件间等待数据服务 Angular,行为主体

[英]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:我在 Angular 中有一个 Behavior Subject 数据服务,它在 admin-layout-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?.当我在用户组件中刷新浏览器时,首先加载当前组件 ngOnInit,我必须有条件检查 userDetails 并向服务器发出新请求,但 admin-layout-component 也在发出请求,我的问题:有一种等待 dataService 的方法,所以我不必使 getUser() 两次? 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:您可以使用 Subject 来存储有关用户的信息,如果需要,您始终可以通过this.userDetails在组件中的任何位置从主题中获取数据:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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