简体   繁体   中英

how to pass data from one component to another component in angular 2?

I am having two components in angular 2 application(ComponentOne and ComponentTwo). ComponentOne needs user details and user preferences to perform some actions, so I get these details from backend services while initializing the ComponentOne.

@Component({
    selector: 'componentOne',
    template: 'componentOneTemplate',
    styles: ['componentOneStyles'],
    providers: []
})
export class ComponentOneComponenet implements OnInit {
    //getting user details
    getUserDetails();

    //getting user preferences
    getUserPreferences();
}

I user router to route from ComponentOne to ComponentTwo.

<router-outlet></router-outlet>

Now again I want userDetails and userPreferences in ComponentTwo. Is there any way to share the data between these two components instead of calling the backend services again?

You could simply cache the data in the service as others have suggested.

Another solution that could be relevant based on use case is to resolve the data in the parent state and get the data from ActivatedRoute in your components. Now when you navigate between component one and two, then the resolvers won't be triggered again. They will be triggered again when the parent state activates again, this might or might not be what you want/need.

path: '',
resolve: [
   userDetails: UserDetailsResolver,
   userPreferences: UserPreferencesResolver
],
children: [{
   path: 'one',
   component: ComponentOne,
},{
   path: 'two',
   component: ComponentTwo,
}]

Yes, the best way and most professional way is to use a global store solution such as ngrx.

ngrx is industry standard and is used to store data that is global to the app.

It makes caching data real easy. I recommend the tutorials on Udemy but they are not free.

Alternatively, if you just want to do a quick cowboy job then use a service and cache the HTTP response in the service like so:

private res: any

public getMyData() {
  return (this.res) ? of(this.res) : this.http.get('/api/some/path')
    .pipe(res => {
      this.res=res
    })
}

and subscribe in the calling code as you would normally:

this.myService.getMyData().subscribe(res => {
  console.log('res', res)
})

You could tweak the getMyData() and pass a boolean to it, the boolean would indicate whether a cached response is sufficient or whether to make the HTTP request again. However, I didn't add this logic as I wanted to keep things simple for you.

PS You would need to provide the service in the root module, or even better just inject the service with:

@Injectable({providedIn: 'root'})

I believe this syntax requires Angular 6.

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