1

我有一个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订阅部分似乎不起作用。

4

1 回答 1

3

您很可能在多个地方使用了“providers: [AlertService]”语句,并且您有两个服务实例。如果您想要单例服务,您应该只在根组件或一些公共父组件中提供服务。提供者是分层的,并且在父组件中提供它将使所有子组件都可以使用相同的实例。

于 2017-02-24T16:23:36.003 回答