Angular2:订阅BehaviorSubject不起作用 [英] Angular2: subscribe to BehaviorSubject not working

查看:391
本文介绍了Angular2:订阅BehaviorSubject不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Alert.Service.ts,它将从另一个服务获取的警报保存在阵列中.在另一个header.component.ts中,我想获取该数组的实时大小.

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.

所以,在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();
}

我希望只要Alert.Service.ts中的alerts数组发生变化,alertListSize就会得到更新.但是,始终是0,它是创建BehaviorSubject时的初始值.似乎订阅部分无效.

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.

推荐答案

您很可能在多个地方使用'providers:[AlertService]'语句,并且您有两个服务实例.您只应在根组件或某些公共父组件上提供服务,如果您想要单例服务.提供程序是分层的,并且在父组件上提供该提供程序将使所有子节点都可以使用相同的实例.

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.

这篇关于Angular2:订阅BehaviorSubject不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆