在Angular 2中的独立组件之间传递数据 [英] Pass data between independent components in Angular 2

查看:76
本文介绍了在Angular 2中的独立组件之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular 2的初学者,现在正在开发小型SPA.在组件Login中,我通过http服务接收一些数据,将数据设置为User类,并且需要该数据在其他一些组件中可用.问题在于组件是完全独立的(没有父子关系).Angular 2中有任何机制可以通过这种方式传递数据吗?

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?

推荐答案

首先,我建议您使用Service在组件之间传递数据.

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

这里有一些示例,说明了组件如何使用3种不同的语言进行通信.方式

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

Angular2-playground演示其代码在Github上可用

假设您要创建服务 S1 并在 app.module.ts 文件中提供该服务,它将创建该服务的 Singleton实例.如果您从组件1 进行服务更改,则可以在组件2 中获得修改后的数据.

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 2中的独立组件之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆