问题
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