首页 > 解决方案 > 共享服务的行为主体使用

问题描述

共享服务.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被调用并且 apingOnInithome.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 同步?

标签: angularobservablebehaviorsubject

解决方案


您可以过滤初始值,

ngOnInt(){
  this.sharedService.intialValue
  .pipe(filter(v=>v))
  .subscribe(res => {
     console.log(res) 
  });
}

推荐阅读