angular - 共享服务的行为主体使用
问题描述
共享服务.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')
}
我确实有家庭组件,通过打开localhost:4200/home
然后刷新它。我相信app.component.ts
被调用并且 apingOnInit
在home.component.ts
被调用之前返回一个值。
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 同步?
解决方案
您可以过滤初始值,
ngOnInt(){
this.sharedService.intialValue
.pipe(filter(v=>v))
.subscribe(res => {
console.log(res)
});
}
推荐阅读
- java - 有没有办法让B
, A 的子类 , 被转换为 A ? - ubuntu-14.04 - 如何将 ubuntu 服务器 14.04 LTS 升级到 18.04 LTS?
- java - Adobe Experience Manager 的 netdiagnostics Java 代理启动错误
- r - R - dbWriteTable 在列名中使用大写字母
- amazon-web-services - 在 DynamoDb 中,Time To Live 删除是否计入写入容量
- apollo - 将嵌套对象写入本地 Apollo 缓存
- r - 如何以 10 分钟的步骤聚合数据
- http - netcat 在 http get 请求上不断超时
- python - strptime 在 docker 容器中运行时抛出错误
- php - 更新到 laravel 5.5 后 EventServiceProvider 无法正常工作