Mat*_*ijs 6 ngrx angular angular-changedetection
我的应用程序组件正在订阅商店选择。我设置ChangeDetectionStrategy为OnPush. 我一直在阅读有关这是如何工作的;需要更新对象引用才能触发更改。然而,当您使用异步管道时,Angular 会期待新的可观察更改并为您执行 MarkForCheck。MarkForCheck那么,当触发订阅并设置channels$新的可观察通道数组时,为什么我的代码不渲染通道(除非我调用)。
@Component({
selector: 'podcast-search',
changeDetection: ChangeDetectionStrategy.OnPush, // turn this off if you want everything handled by NGRX. No watches. NgModel wont work
template: `
<h1>Podcasts Search</h1>
<div>
<input name="searchValue" type="text" [(ngModel)]="searchValue" ><button type="submit" (click)="doSearch()">Search</button>
</div>
<hr>
<div *ngIf="showChannels">
<h2>Found the following channels</h2>
<div *ngFor="let channel of channels$ | async" (click)="loadChannel( channel )">{{channel.trackName}}</div>
</div>
`,
})
export class PodcastSearchComponent implements OnInit {
channels$: Observable<Channel[]>;
searchValue: string;
showChannels = false;
test: Channel;
constructor(
@Inject( Store) private store: Store<fromStore.PodcastsState>,
@Inject( ChangeDetectorRef ) private ref: ChangeDetectorRef,
) {}
ngOnInit() {
this.store.select( fromStore.getAllChannels ).subscribe( channels =>{
if ( channels.length ) {
console.log('channels', !!channels.length, channels);
this.channels$ = of ( channels );
this.showChannels = !!channels.length;
this.ref.markForCheck();
}
} );
}
Run Code Online (Sandbox Code Playgroud)
我尝试了多种解决方案,包括使用 asubject和 调用next,但除非我调用 MarkForCheck,否则这不起作用。
谁能告诉我怎样才能避免打电话markForCheck?
这可能有点难以解释,但我会尽我最大的努力。当您的原始 Observable(商店)发出时,它不会绑定到模板。由于您使用的是 OnPush 更改检测,因此当此可观察对象发出时,由于缺乏绑定,它不会将组件标记为更改。
您正在尝试通过覆盖组件属性来触发更改标记。即使您在组件属性本身上创建新引用,这也不会标记组件进行更改,因为组件正在更改其自己的属性,而不是将新值推送到组件上。
您认为异步管道在发出新值时标记组件进行更改是正确的。您可以在此处的 Angular 源代码中看到这一点:https ://github.com/angular/angular/blob/6.0.9/packages/common/src/pipes/async_pipe.ts#L139
然而,您会注意到,只有当您与管道async一起使用的值(称为 ),即与管道已记录为正在发出的 Observable 的对象相匹配时,这才有效。asyncthis._objasync
由于您正在执行channels$ = <new Observable>,async === this._obj实际上是不正确的,因为您正在更改对象引用。这就是为什么您的组件没有标记为更改的原因。
您还可以在我整理的 Stackblitz 中看到这一点的实际效果。第一个组件覆盖传递给async管道的 Observable,而第二个组件则不覆盖它并通过响应发出的更改来更新数据——这就是您想要做的:
https://stackblitz.com/edit/angular-pgk4pw(我使用它timer是因为它是模拟第三方未绑定 Observable 源的简单方法。使用输出绑定(例如单击更新)更难以设置,因为如果它是在同一组件中完成输出操作将触发更改标记)。
你并没有失去一切——我建议你this.channels$ = this.store.select(...)这样做。管async柄.subscribe为您服务。如果您正在使用async管道,则无论如何都不应该使用.subscribe。
this.channels$ = this.store.select(fromStore.getAllChannels).pipe(
filter(channels => channels.length),
// channels.length should always be truthy at this point
tap(channels => console.log('channels', !!channels.length, channels),
);
Run Code Online (Sandbox Code Playgroud)
请注意,您也可以与异步管道一起使用ngIf,这应该消除您对showChannels.
| 归档时间: |
|
| 查看次数: |
4692 次 |
| 最近记录: |