【发布时间】: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