有关组件交互的指南非常有用:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
您应该使用服务,而不是简单的输出事件.然后,yet-another-presentational-component
可以发出对服务的更改,同时
smart-component-with-api-access
可以订阅服务并相应地采取行动.
例:
一个简单的通知服务"notification.service.ts":
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class NotificationService { constructor() { } private notificationSource = new Subject(); public notificationReceived = this.notificationSource.asObservable(); notify(newMessage: string) { this.notificationSource.next(newMessage); console.log(message); } }
然后在smart-component-with-api-access中导入服务,添加到构造函数并订阅通知:
import { NotificationService } from './shared/services/notification.service'; ... export class SmartComponentWithAPIAccess { constructor(private notificationService: NotificationService) { this.notificationService.notificationReceived.subscribe( message => { // do something with message such as access API } ); } }
在另一个演示组件中导入通知服务并在构造函数中声明如上所述,然后当您要触发通知/事件时:
this.notificationService.notify("I have a message");