Pass data between independent components in Angula

2019-09-06 15:03发布

问题:

I'm a beginner in Angular 2 and now developing small SPA. In component Login I receive some data via http service, set data into class User and need that data to be available in some other components. The problem is that components are completely independent (don't have parent-child relation). Are there any mechanisms in Angular 2 to pass data in that way?

回答1:

First of all I would like to recommends you to use Service to pass data between components.

Here are some example how components can communicate using 3 different. ways,

Angular2-playground Demo its code available on Github

Suppose if you are creating service S1 and providing that service in app.module.ts file it will create a Singleton instance of that service. If you make changes in service from Component 1, than you will can get that modified data in Component 2.

Or you can do like that add service in separate module for separate functionality, so that service can be accessible in that module only.

Summary: you can use services to passing data between components, it will very helpful.



标签: angular