角度@Input变量在可观察(生命周期)中是否是最新的?

时间:2017-09-18 13:01:32

标签: angular rxjs observable

我正在使用名为“genericC”的通用组件来获取一些数据,并将它们作为输入中的obervable发送到其他组件中以显示它们。

但是,当我尝试在更新数据的目标中向此通用组件发送事件的发送时,我遇到了问题,因为来自通用组件的输入的userId变量仅在ngOnChanges中更新() 方法。 当我使用一个可以每次监听并等待允许刷新数据的observable时,情况并非如此。

也许我想念Angular

的数据生命周期

这是我的代码,在跳跃中,比我以前的文字更清晰:

Component A, I want to say, go to update the data via this call : this.uiService.refreshFetchNotify("family");

Component GENERIC:
@Input() userId: string;
@Input() type: string;

..... constructor and declarations of variable

this.refreshFetch$ = this.uiService.refreshFetchChanged().startWith(this.type);

ngOnChanges(changes: SimpleChanges) {
     // this.userId ===> is up to date as expected
}

this.searchTxt$ = this.searchForm.valueChanges
      .startWith(null)
      .combineLatest(this.refreshFetch$) // this.userId just after is NOT UP TO DATE yet
      .switchMap(([_, refresh]) => {
          if (this.type === 'family' && refresh === this.type)
              return this.filterFamiliesUser(
                this.userId
           );
           else() {
              // something else here
           }
       });

提前感谢您的帮助

编辑:在这个例子中,我把它称为通用组件,但即使不是这样,就像现在使用我的应用程序,我使用服务,我也遇到了这个问题,因为我继续使用一些依赖于@input组件

1 个答案:

答案 0 :(得分:0)

您是对的,valueChanges将在ngOnChanges之前触发。

valueChanges事件(您当前映射到_)应该包含最新值。使用它而不是this.userId。根据{{​​3}}:

  

插值绑定是显示名称更改的更简单方法。   订阅可观察的表单控件属性非常方便   触发组件类中的应用程序逻辑。

插值绑定(例如this.userId)用于显示路径。

valueChanges用于控制路径。你不应该把两条路径结合起来。

也有一些不太理想的解决方案。

  • 您可以在valueChanges路径上执行所有操作,只需向您的可观察链添加do即可更新this.userId
  • 您可以通过创建自己的主题并从ngOnChanges调用next()并永不订阅ngOnChanges来完成valueChanges路径上的所有操作。

但是,最佳解决方案只是在控制路径中使用值更改事件本身,并仅使用this.userId进行显示。