最后
我管理自己在数组中使用一个BehaviorSubject。
@Injectable()
export class AlertService {
private queue: Alert[] = new Array<Alert>();
private behaviorSubjectQueue: BehaviorSubject<Alert[]> = new BehaviorSubject<Alert[]>(this.queue);
constructor() {
}
getInstance() {
return this.behaviorSubjectQueue;
}
push(type: string, title: string, message: string) {
let alert = new Alert(type, title, message);
this.queue.push(alert);
this.behaviorSubjectQueue.next(this.queue);
window.setTimeout(_ => {
this.pop();
},3000);
}
pop() {
this.queue.pop();
this.behaviorSubjectQueue.next(this.queue);
}
}
组件保持不变,但在每次推送和弹出操作时都会收到通知。
谢谢大家的帮助!