【发布时间】:2018-12-11 11:35:27
【问题描述】:
shared-service.ts
intialValue: BehaviorSubject<string> = new BehaviorSubject(null);
setInitialValue(value: any){
this.intialValue.next(value)
}
app.component.ts
async ngOnInit(){
//api call
await this.sharedService.setInitialValue('api return value')
}
我确实有 home 组件,通过打开 localhost:4200/home 然后刷新它。我相信app.component.ts 被调用并且api 在ngOnInit 被调用之前返回一个值。
home.component.ts
ngOnInt(){
this.sharedService.intialValue.subscribe(res => {
console.log(res) //it should be 'api return value' which is set in app.component but it showing null.
});
}
我观察到的是home.component.ts 的ngOnInit 在api success 调用完成之前被调用。我该如何克服这种情况,我是否以错误的方式使用了 behaviorSubject 和 angular 组件,javascript 同步?
【问题讨论】:
-
如果我理解你写的内容,只需将
BehaviorSubject更改为Subject-> intialValue = new Subject(); -
主题需要先订阅才能使用该值。所以正常
home.component.ts加载ngOnInit被调用但intialValue不是emitting任何值(在第一次订阅时)。通过使用主题我可以实现刷新组件如你所说但在正常加载时失败。
标签: angular observable behaviorsubject