根据本指南:Parent and children communicate via a service
我想使用共享服务作为EventEmitter的替代,因为EventEmitter只在父组件和子组件之间进行通信 . 在我的情况下情况并非如此,但两个组件共享相同的服务(MasterdataService) .
看来我的订阅无法拦截公告 . 除了已触发通知的日志信息之外,浏览器控制台中也没有错误 . 我真的很想知道我在这里失踪了什么 .
MasterdataService
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class MasterdataService {
private _updateAnnouncedSource = new Subject<string>();
updateAnnounced$ = this._updateAnnouncedSource.asObservable();
announceUpdate(value: string) {
console.log('announcement to update list has been triggered');
this._updateAnnouncedSource.next(value);
}
}
MasterdataComponent (宣布更新)
@Component({
providers: [MasterdataService]
})
export class MasterdataComponent {
constructor(private masterdataService: MasterdataService) {}
newMerchant(merchantIdInput: HTMLInputElement, merchantNameInput: HTMLInputElement) {
this.masterdataService.announceUpdate('newMerchant');
}
}
MasterdataListComponent (订阅主题)
@Component({
providers: [MasterdataService]
})
export class MasterdataListComponent {
subscription:Subscription;
constructor(private masterdataService:MasterdataService) {
this.subscription = this.masterdataService.updateAnnounced$.subscribe(
value => {
console.log('update announcement received... updating list with value ', value);
this.merchants = this.masterdataService.getAllMerchants();
})
}
}
1 回答
我的问题不是代码,而是我在组件中使用/声明服务的方式 . 通过在装饰器中的两个组件中定义该Service
angular为每个组件实例化单独的服务 . 这样,不能执行两个组件之间的通信 .
由于我有一个根组件(AppComponent),我可以在该装饰器中声明服务,而角度通过将服务作为两个组件类的构造函数中的参数来处理其余的(DI a.k.a依赖注入) .