Angular2:订阅BehaviorSubject不起作用
问题描述:
我有一个Alert.Service.ts
,它保存从阵列中的其他服务获取的警报。在另一个header.component.ts
中,我想获得该数组的实时大小。Angular2:订阅BehaviorSubject不起作用
所以,在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();
}
我期待alertListSize
只要alerts
阵列中Alert.Service.ts
改变得到更新。但是,始终为0
这是创建BehaviorSubject
时的初始值。看来订阅部分不起作用。
答
您很可能在多个地方使用'providers:[AlertService]'语句,并且您有两个服务实例。您应该只在根组件上提供服务,或者如果您需要单件服务,则应该提供一些常见的父组件。提供者是分层的,并且在父组件上提供它将使所有孩子都可以使用同一个实例。
如果您尝试并直接订阅'alertItemSource'(并将其公开)是正确返回的值? – PRacicot
@PRacicot我试过了,值也没有更新。 –
通过查看您的代码,我发现'AlertService'构造函数有一个参数。但是在你的'header.component.ts'构造函数中,你有了基本的DI。在我目前的ng2项目中,我所有的Injectable服务都有空的构造函数。我建议尝试模拟一个虚假的'MonitorService'并且有一个空的构造函数来查看BehaviorSubject是否实际运行并返回正确的值。 – PRacicot