基于Angular 2的docs,您可以使用@Input轻松地将数据从组件传递到另一个组件 .
例如,我可以像这样设置父级:
import { Component } from '@angular/core';
import { HEROES } from './hero';
@Component({
selector: 'hero-parent',
template: `
<h2>{{master}} controls {{heroes.length}} heroes</h2>
<hero-child *ngFor="let hero of heroes"
[hero]="hero"
[master]="master">
</hero-child>
`
})
export class HeroParentComponent {
heroes = HEROES;
master: string = 'Master';
}
并获取子组件中的数据,如下所示:
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
所以很明显,将 [hero]="data"
传递给父组件的模板(当然在子选择器中)并将它们处理到子组件中 .
But here's the issue.
我的子组件DOM元素(在本例中为 <hero-child>
)在父模板中不可用,而是在 <router-outlet>
元素中加载 .
那么如何将数据传递给子路径组件呢?是不是输入正确的方法?我想避免使用double,treble等调用来获取我父路由/组件中已有的相同数据 .
3 回答
我不相信有任何方法可以将对象作为输入传递给路由到的组件 . 我已经通过使用具有observable的服务来完成此操作,以在父组件和一个或多个子组件之间共享数据 .
基本上,父组件调用服务并将所需的任何数据推送到它 . 在我的情况下,它只是一个ID,但它可以是任何东西 . 然后,服务可以对该数据执行某些操作(或不执行) . 在我的示例中,我正在调用服务器以根据ID获取公司,但如果您已经拥有所需的对象,则不需要这样做 . 然后,它将对象推送到子组件中订阅的Observable流 .
父组件:
服务:
子组件
考虑为
@Input()
或@Output()
创建一个Angular2服务,该服务将通过多个层或不相关的组件 .你可以通过以下方式实现目标:
创建一个为您保留某些状态的服务 . 因此子组件可以在以后访问它 .
使用路由器传递数据(动态路由,queryParam,param) . 例如:users /:id => users / 23
使用状态管理库传递数据 . 例如:Redux