简体   繁体   English

在Angular 2中的独立组件之间传递数据

[英]Pass data between independent components in Angular 2

I'm a beginner in Angular 2 and now developing small SPA. 我是Angular 2的初学者,现在正在开发小型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. 在组件Login中,我通过http服务接收一些数据,将数据设置为User类,并需要该数据在其他一些组件中可用。 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? Angular 2中是否有任何以这种方式传递数据的机制?

First of all I would like to recommends you to use Service to pass data between components. 首先,我建议您使用Service在组件之间传递数据。

Here are some example how components can communicate using 3 different. 这是一些示例,说明组件如何使用3种不同的语言进行通信。 ways, 方法,

Angular2-playground Demo its code available on Github Angular2-playground演示其代码可在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 . 假设您要创建服务S1并在app.module.ts文件中提供该服务,它将创建该服务Singleton实例 If you make changes in service from Component 1 , than you will can get that modified data in Component 2 . 如果您从组件1更改服务,则可以在组件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. 简介:您可以使用服务在组件之间传递数据,这将非常有帮助。

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

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