【问题标题】:Angular2: subscribe to BehaviorSubject not workingAngular2:订阅 BehaviorSubject 不起作用
【发布时间】:2016-07-05 18:28:35
【问题描述】:

我有一个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();
}

我预计只要Alert.Service.ts 中的alerts 数组发生更改,alertListSize 就会更新。但是,它始终是 0,这是创建 BehaviorSubject 时的初始值。订阅部分好像不行。

【问题讨论】:

  • 如果您尝试直接订阅alertItemSource(并将其公开),返回的值是否正确?
  • @PRacicot 我试过了,值也没有更新。
  • 通过查看您的代码,我看到您的AlertService 构造函数有一个参数。但是在您的 header.component.ts 构造函数中,您拥有基本的 DI。在我当前的 ng2 项目中,我所有的 Injectable 服务都有空的构造函数。我建议尝试模拟一个假的MonitorService 并使用一个空的构造函数来查看 BehaviorSubject 是否实际运行并返回正确的值。
  • @PRacicot 很抱歉让MonitorService 感到困惑。它实际上是在父级app.component.ts 中注入的。所以,它可以在Monitor.Service.ts 中访问。在注释掉AlertService 中的所有MonitorService 后,值会更新。由于AlertService 依赖于慢速MonitorSerivce,所以在构造`AlertService 时if (MonitorService.alertAgg != undefined) 为false。
  • @PRacicot 有没有办法在 MonitorService 完全准备好之后强制构造 AlertService

标签: angular rxjs subject behaviorsubject


【解决方案1】:

您很可能在多个地方使用了“providers: [AlertService]”语句,并且您有两个服务实例。如果您想要单例服务,您应该只在根组件或一些公共父组件中提供服务。提供者是分层的,在父组件中提供它将使所有子组件都可以使用同一个实例。

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    相关资源
    最近更新 更多