的问题是我怎么从列表后的值到后期的细节,使其立即作出反应?我假设应该有一个Observable在后期细节等待变化。我也假设它应该观看输入属性。问题是:我可以从列表中获取值并将其作为输入属性发送给后期详细信息?可以(也应该)通过父组件传递它,还是应该为此定义一个服务?
这种情况非常简单 - 后期列表需要指示何时选择某个项目,并将该“selectedItem”信息传递给后期细节以供显示。
如果我正在处理这种情况,我会使用简单的输入和输出(即属性和事件绑定)在组件之间传递信息,使用父组件作为通信的中介。您正在通过父组件进行路由 - 具体来说,后期列表指示何时选择帖子以及该帖子是什么,而帖子详细信息仅显示传递给它的任何帖子。
因此,后列表需要一个名为itemSelect的@Output EventEmitter属性或其他适当的东西。此属性的目的是通知任何关心何时选择项目以及该项目是什么的人。
PostListComponent:
export class PostDetailComponent {
.....
@Output() postSelect = new EventEmitter();
// whenever a post is selected, you call this.postSelect.emit(selectedPost)
// to notify others which post is selected
在PostDetailComponent:
export class PostDetailComponent {
.....
// this is your property binding
// used to get data in real time in to the component for display
@Input() post;
最后,父组件需要交物业接收来自列表发布更新,并通过这些更新后期细节。
为父级
的为父级只是监听来自PostList更新,并接收他们,分配事件(在模板中的$事件值),其内部岗位性质,实质这又被推送到PostDetail。
@Component({
.......
template: `
<post-list (postSelect)="post = $event"> </post-list>
<post-detail [post]="post"> </post-detail>
`
})
export class ParentComponent {
post: any; // brokers the communication between the two child components
.......
这就是我的情况。
您可以使用服务来代理通信,但通常只有当通信方式复杂或两个组件在视图层次结构中彼此不接近时才需要,因此很难从一个组件到另一个。但在你的情况下,服务可能是矫枉过正的。
See the docs for more info.
因为你提到Observable,我们可以假设这是一个关于angular2的问题,并且与angularjs无关? – Claies
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service – echonax
是的,Angular 2,更确切地说是Angular 4.感谢您的链接。 –