简体   繁体   English

Angular2:订阅BehaviorSubject不起作用

[英]Angular2: subscribe to BehaviorSubject not working

I have an Alert.Service.ts which saves alerts fetched from another service in an array. 我有一个Alert.Service.ts ,它保存从数组中的另一个服务获取的警报。 In another header.component.ts , I want to get the real-time size of that array. 在另一个header.component.ts ,我想获得该数组的实时大小。

So, in Alert.Service.ts I have 所以,在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);
}

And, in header.component.ts , I have 而且,在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();
}

I expect the alertListSize gets updated as long as the alerts array in Alert.Service.ts changed. 我预计alertListSize被更新,只要alerts数组中Alert.Service.ts改变。 However, it's always 0 which is the initial value when the BehaviorSubject is created. 但是,它始终为0 ,这是创建BehaviorSubject时的初始值。 It seems that the subscribe part doesn't work. 似乎订阅部分不起作用。

You are most likely using the 'providers: [ AlertService ] ' statement in multiple places, and you have two instances of your service. 您最有可能在多个地方使用'providers:[AlertService]'语句,并且您有两个服务实例。 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. 提供者是分层的,并且在父组件处提供它将使所有子组件都可以使用相同的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM