Angular2: subscribe to BehaviorSubject not working

孤街浪徒 提交于 2019-12-11 05:08:41

问题


I have an Alert.Service.ts which saves alerts fetched from another service in an array. In another header.component.ts, I want to get the real-time size of that array.

So, in Alert.Service.ts I have

@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);
}

And, in header.component.ts, I have

@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();
}

I expect the alertListSize gets updated as long as the alerts array in Alert.Service.ts changed. However, it's always 0 which is the initial value when the BehaviorSubject is created. It seems that the subscribe part doesn't work.


回答1:


You are most likely using the 'providers: [ AlertService ] ' statement in multiple places, and you have two instances of your service. You should only provide your services at the root component, or some common parent component if you want a singleton service. Providers are hierarchical , and providing it at a parent component will make the same instance available to all children.



来源:https://stackoverflow.com/questions/38210235/angular2-subscribe-to-behaviorsubject-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!