问题
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