Angular2:订阅BehaviorSubject不起作用

时间:2016-07-05 18:28:35

标签: angular rxjs subject behaviorsubject

我有一个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时的初始值。订阅部分似乎无法正常工作。

1 个答案:

答案 0 :(得分:3)

您最有可能在多个地方使用'providers:[AlertService]'语句,并且您有两个服务实例。如果需要单例服务,则只应在根组件或某些公共父组件上提供服务。提供者是分层的,并且在父组件处提供它将使所有孩子都可以使用相同的实例。