我的应用程序组件正在订阅商店选择。我设置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();
}
} );
}
我尝试了多种解决方案,包括使用 asubject
和调用next
,但除非我调用 MarkForCheck,否则它不起作用。
谁能告诉我如何避免打电话markForCheck
?