我有一个Alert.Service.ts
将从另一个服务获取的警报保存在一个数组中。在另一个header.component.ts
中,我想获得该数组的实时大小。
所以,在Alert.Service.ts
我有
@Injectable()
export class AlertService {
public static alerts: any = [];
// Observable alertItem source
private alertItemSource = new BehaviorSubject<number>(0);
// Observable alertItem stream
public alertItem$ = this.alertItemSource.asObservable();
constructor(private monitorService: MonitorService) {
if (MonitorService.alertAgg != undefined) {
AlertService.alerts = MonitorService.alertAgg['alert_list'];
AlertService.alerts.push({"id":111111,"severity":200}); //add a sample alert
this.updateAlertListSize(AlertService.alerts.length);
MonitorService.alertSource.subscribe((result) => {
this.updateAlertList(result);
});
}
}
private updateAlertList(result) {
AlertService.alerts = result['alert_list'];
this.updateAlertListSize(AlertService.alerts.length);
}
// service command
updateAlertListSize(number) {
this.alertItemSource.next(number);
}
而且,在 中header.component.ts
,我有
@Component({
selector: 'my-header',
providers: [ AlertService ],
templateUrl: 'app/layout/header.component.html',
styles: [ require('./header.component.scss')],
})
export class HeaderComponent implements OnInit, OnDestroy {
private subscription:Subscription;
private alertListSize: number;
constructor(private alertSerivce: AlertService) {
}
ngOnInit() {
this.subscription = this.alertSerivce.alertItem$.subscribe(
alertListSize => {this.alertListSize = alertListSize;});
}
ngOnDestroy() {
// prevent memory leak when component is destroyed
this.subscription.unsubscribe();
}
我希望alertListSize
只要alerts
数组Alert.Service.ts
更改就会更新。但是,它始终是创建0
时的初始值。BehaviorSubject
订阅部分似乎不起作用。