Angular 2中的不同模块组件通信 [英] Different module components communication in Angular 2

查看:140
本文介绍了Angular 2中的不同模块组件通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,我希望它可以将数据传递到另一个模块中的另一个组件.实际上,我的app.component是这些子模块的父级.我希望每个子模块都将一些数据发送到app.component.但是他们只有在路由的情况下才是孩子和父母.我猜他们实际上不是父母和孩子.

I have One component and I want it to pass data to another one which is in another module. Actually my app.component is a parent of these children modules. And I want each child module to send some data to app.component. But they are children and parent only in a sence of routing. So they aren't actually parents and children, I guess.

我的意思是,我对app.component的模板看起来像这样:

I mean, my templet for app.component looks like this:

  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav navbar-left">
      <li><a routerLink="link1" routerLinkActive="active">Page1</a></li>
      <li><a routerLink="link2" routerLinkActive="active">Page2</a></li>
      <li><a routerLink="link3" routerLinkActive="active">Page3</a></li>
      <li><a routerLink="link4" routerLinkActive="active">Page4</a></li>
    </ul>
  </div>
</nav>
<div *ngIf="needsSidebar" id="sidebar">some content</div>
<div>
  <router-outlet></router-outlet>
</div>

因此,app.component与这些模块及其组件没有直接连接.我尝试使用Output,但是由于组件来自不同的模块,所以它失败了.我迷失了该怎么办.我希望我的儿童"模块将数据发送到app.module上,以告知它们是否需要侧边栏以及侧边栏应显示哪些内容.我该怎么做?

So app.component has no direct connection with these modules and theirs components. I tried to use Output but since components are from different modules it failed. I'm lost in what should I do. I want my "children" modules to send data to up the app.module to tell it if they needs a sidebar and which content should sidebar show. How can I do it?

推荐答案

模块之间的关系并不重要.重要的是,如果组件是组件视图中的子代.在这种情况下,您可以使用Angulars绑定语法.在其他情况下,请使用共享服务.有关详细信息,请参见 https://angular.io/docs/ts/latest/cookbook/component-communication.html

It doesn't matter how the modules are related. What matters is, if the components are children in a components view. In this case you can use Angulars binding syntax. In other cases use a shared service. For details see https://angular.io/docs/ts/latest/cookbook/component-communication.html

还重要的是,您在其中将共享服务添加为提供程序.如果将其添加到组件,则仅此组件的一个实例及其子代和后代共享此服务实例. 如果将服务添加到@NgModule()的提供程序,则单个实例将与整个应用程序共享(对于非延迟加载的模块).

What also matters is, where you add a shared service as provider. If you add it to a component, only an instance of this component and its children and descendants share this service instance. If you add a service to providers of @NgModule() a single instance is shared with the whole application (for non-lazy loaded modules).

这篇关于Angular 2中的不同模块组件通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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