Tim*_*ter 2 ngrx angular angular-changedetection
我在我的视图中设置了一个内插值:
{{firstName}}
当它绑定到的字段的值发生变化时,它不会更新。但是,该值正在更改 - 如果我将其注销到订阅内的控制台,我会看到更新后的值。它只是不会在 UI 中更新。
这是相关的代码:
从我的组件订阅:
private subscribeToCurrentPerson(): void {
this.tState$ = this.store
.pipe(select(selectors.getCurrentPerson), takeWhile(() => this.componentActive))
.subscribe((cp: Person) => {
if (cp) {
const name: string = cp.primaryName.value.parsedValue.givenNames[0];
this.firstName = name;
console.log('name: ' + name); // <-- this shows correct new value
}
});
}
Run Code Online (Sandbox Code Playgroud)
subscribeToCurrentPerson从组件的 ngOnInit 调用。在此之前,该firstName属性是未定义的。
该selectors.getCurrentPerson选择是这样的:
export const getCurrentPerson: MemoizedSelector<{}, Person> =
createSelector(getTState, (tState: ITState) => {
console.log('selector: ', tState); // <-- this logs the correct new value
return tState ? tState.currentPerson : null;
});
Run Code Online (Sandbox Code Playgroud)
currentPerson选择器返回的值是一个新创建的对象。这发生在应用程序的第一次运行时,因此在此之前tState是未定义的。
如果我注入ChangeDetectorRef我的构造函数并cdr.detectChanges()在订阅中调用,UI 就会更新。但在我看来,我通常不需要ChangeDetectorRef像这样使用它,它应该“正常工作”。
我认为问题在于我嵌套很深的属性 ( cp.primaryName.value.parsedValue.givenNames)。我从一个非 ngRx 项目继承了这些实体,但我认为我的下一步是尝试扁平化该结构,看看这是否能让 ngRx 和 Angular 变化检测器更快乐。
还有什么我想念的吗?
谢谢,
电讯
更新
通过简单地更新订阅内组件上的本地属性,我已经将深度嵌套的属性排除在外。所以这个subscribeToCurrentPerson函数现在看起来像这样:
private subscribeToCurrentPerson(): void {
this.tState$ = this.store
.pipe(select(selectors.getCurrentPerson), takeWhile(() => this.componentActive))
.subscribe((cp: Person) => {
this.myProp = 'goodbye';
this['newProp'] = 'world';
});
}
Run Code Online (Sandbox Code Playgroud)
myProp是我添加用于测试的组件上的现有属性。
newProp在通过订阅内的括号表示法添加之前不存在。结果如下:
myProp未更新 - 它显示了我在声明时分配给它的值。但是,如果我在声明属性时不分配值,则订阅中分配的值会正确显示在 UI 中。newProp 是在UI显示正确我现在完全不知所措。 似乎一旦一个属性有一个值,它就永远不会在 UI 中更新,即使值本身确实发生了变化(我可以通过在更新值后登录到控制台来判断)。
我没有ChangeDetectionStrategy为组件明确设置,所以它是Default.
如果我打电话一切正常detectChanges,但我认为这没有必要。
当父组件将其更改检测策略设置为时OnPush,该父组件的树将不会被 angular 的更改检测机制检查,尽管ngOnChanges每次任何@Input属性更改时仍会调用此父组件及其子组件的方法。要让 angular 知道这棵树中的某个组件需要更新,请将 aChangeDetectorRef注入该组件并使用其 API 通知 angular 有关更新的信息,例如detectChanges或markForCheck
| 归档时间: |
|
| 查看次数: |
1578 次 |
| 最近记录: |