我有一个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
时的初始值。订阅部分似乎无法正常工作。
答案 0 :(得分:3)
您最有可能在多个地方使用'providers:[AlertService]'语句,并且您有两个服务实例。如果需要单例服务,则只应在根组件或某些公共父组件上提供服务。提供者是分层的,并且在父组件处提供它将使所有孩子都可以使用相同的实例。