0
我有一個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
時的初始值。看來訂閱部分不起作用。
如果您嘗試並直接訂閱'alertItemSource'(並將其公開)是正確返回的值? – PRacicot
@PRacicot我試過了,值也沒有更新。 –
通過查看您的代碼,我發現'AlertService'構造函數有一個參數。但是在你的'header.component.ts'構造函數中,你有了基本的DI。在我目前的ng2項目中,我所有的Injectable服務都有空的構造函數。我建議嘗試模擬一個虛假的'MonitorService'並且有一個空的構造函數來查看BehaviorSubject是否實際運行並返回正確的值。 – PRacicot