【问题标题】:behavior subject usage for shared services共享服务的行为主体使用
【发布时间】: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.tsngOnInitapi success 调用完成之前被调用。我该如何克服这种情况,我是否以错误的方式使用了 behaviorSubject 和 angular 组件,javascript 同步?

【问题讨论】:

  • 如果我理解你写的内容,只需将BehaviorSubject 更改为Subject -> intialValue = new Subject();
  • 主题需要先订阅才能使用该值。所以正常home.component.ts加载ngOnInit被调用但intialValue不是emitting任何值(在第一次订阅时)。通过使用主题我可以实现刷新组件如你所说但在正常加载时失败。

标签: angular observable behaviorsubject


【解决方案1】:

可以过滤初始值,

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

【讨论】:

  • 过滤器的用途?
  • 那么您真的关心方法执行的顺序而不是事件数据吗,因为您已经使用了 BehaviorSubject?
  • 是的,执行顺序是高优先级。行为主题可以替换,但我使用它的原因是它存储了以前的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多