Angular 角度2:订阅行为主体不工作
我有一个Angular 角度2:订阅行为主体不工作,angular,rxjs,subject,behaviorsubject,Angular,Rxjs,Subject,Behaviorsubject,我有一个Alert.Service.ts,它将从另一个服务获取的警报保存在一个数组中。在另一个header.component.ts中,我想获得该数组的实时大小 因此,在Alert.Service.ts中 @Injectable() export class AlertService { public static alerts: any = []; // Observable alertItem source private alertItemSource = new BehaviorSu
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);
}
我希望只要
Alert.Service.ts
中的alerts
数组发生更改,alertListSize
就会得到更新。但是,它总是0
,这是创建BehaviorSubject
时的初始值。“订阅”部分似乎不起作用。您很可能在多个位置使用了“提供者:[AlertService]”语句,并且您有两个服务实例。您应该只在根组件上提供服务,如果您想要单例服务,则应该在某个公共父组件上提供服务。提供者是分层的,在父组件上提供它将使所有子组件都可以使用相同的实例。如果您尝试直接在alertItemSource上订阅(并将其公开),返回的值是否正确?@PRacicot我尝试过,该值也不会更新。通过查看您的代码,我看到您的AlertService
构造函数有一个参数。但是在header.component.ts
构造函数中,您拥有基本的DI。在我当前的ng2项目中,我所有的可注入服务都有空构造函数。我建议尝试模拟一个假的MonitorService
,并使用一个空构造函数来查看BehaviorSubject是否实际运行并返回正确的值。@PRacicot很抱歉让人困惑的MonitorService
。它实际上是在父级app.component.ts
中注入的。因此,可以在Monitor.Service.ts
中访问它。在注释掉AlertService
中的所有MonitorService
后,该值将被更新。由于AlertService
依赖于慢速MonitorService
,因此在构建“AlertService”时,如果(MonitorService.alertAgg!=未定义)
为假。@PRacicot有没有办法在MonitorService
完全准备好后强制构建AlertService
?
@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();
}