我没有使用Angular2中的rxjs Observable来构建我的通知系统。
我已经建立了这样的通知服务:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class NotificationService {
private notifications: BehaviorSubject<{}> = new BehaviorSubject<{}>({});
constructor() {
}
notify(message: string, type: string) {
// Seems to do nothing ?
this.notifications.next(
{ 'type': type, 'message': message }
);
}
notifyError(message: string) {
this.notify(message, 'error');
}
notifyInfo(message: string) {
this.notify(message, 'info');
}
notifyWarning(message: string) {
this.notify(message, 'warning');
}
notifyPrimary(message: string) {
this.notify(message, 'primary');
}
notifySuccess(message: string) {
this.notify(message, 'success');
}
onNotification(): Observable<{}> {
return this.notifications.asObservable();
}
}
似乎this.notifications.next什么都不做,或订阅此服务的组件无法接收通知。
在这个组件中我有这个代码:
ngOnInit() {
this.notificationService.onNotification().subscribe(
notification => { data => console.log("notification", data.message) },
error => console.log(error)
);
}
我可以在NotificationService的notify *方法中记录由其他组件触发的通知。
这是我的案例的追加者:http://plnkr.co/edit/A8G22puWedxF5fAWyvYI