angular2 is it possible to share observable data with other components?

こ雲淡風輕ζ 提交于 2019-12-12 05:14:19

问题


I have a service that GETS a user via a RESTful api. It uses the Observable implementation.

I also have a parent component with 8 child components.

I want to know if and how I can make a single HTTP request in the parent component, to get the user and share it amongst its children components.

Here's the call to define user in the parent:

this.userApi.getUser(id)
        .subscribe(response => {this.user = response;},
                    error => error);

I've imported and injected the user model into the constructor() of each component like so:

constructor(public user: User){}

Once the user is defined in the parent, I have a button which fires a console.log(user) in the child components, it comes back as undefined.


回答1:


If you want to make only a single HTTP request and share user data, create a service, which will store your user object. It would be available for each component (root and all childrens) in module.

Also you could use ngRx store idea - https://github.com/ngrx/store. Advantage of this solution is that you could subscribe user store in every fragment of application.



来源:https://stackoverflow.com/questions/39006427/angular2-is-it-possible-to-share-observable-data-with-other-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!