由于ngIf语句,存储选择未运行 [英] store select not running because of ngIf statement
问题描述
我正在忙于MeteorJS和RxJS,它们正在退出,但有时也有些混乱. 我当前的问题仅是Angular NgRx问题,与MeteorJS不相关.
I am busy with MeteorJS and RxJS, which is exiting but also a bit confusing sometimes. My current question is an Angular NgRx question only, not related to MeteorJS.
如您在示例中看到的,有一个基于showChannels
的ngIf
.此布尔值设置为false
.但是,内部的async for循环引用到了我的store.select.
但是,由于存在ngIf,因此永远不会执行管道中的运算符.这似乎是一个僵局.
如何启用订阅才能开始工作?
As you can see in the example, there is a ngIf
based on showChannels
. This boolean is set to false
. However, the async for loop inside is referenced to my store.select.
However, operators in the pipe are never executed, because of the ngIf. It seems to be a deadlock.
How do I enable the subscription to start working?
当我进行搜索时,它会将频道添加到商店中,并且如果ngFor
循环中没有ngIf
,则store.select
将起作用.
When I do a search it adds Channels to the store, and the store.select
would work if there would be no ngIf
around the ngFor
loop.
当我将if替换为*ngIf="(channels$ | async) ?.length !== 0"
时,它将起作用,但是当我进行一次搜索时,tap
将运行两次.
When I recplace the if to *ngIf="(channels$ | async) ?.length !== 0"
it will work, but then the tap
is run twice when I do one search.
带有markForCheck
很好地工作.在不使用subscribe
时有什么最佳解决方案的建议?
The commented store.select with the subscribe actually works well using the markForCheck
. Any suggestions on what the best solution while not using the subscribe
?
@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, OnDestroy {
channels$: Observable<Channel[]>;
searchValue: string;
showChannels = false;
constructor(
private store: Store<fromStore.PodcastsState>,
) {}
ngOnInit() {
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);
this.showChannels = !!channels.length;
}),
);
// this.store.select( fromStore.getAllChannels ).subscribe( channels =>{
// console.log('channels', !!channels.length, channels);
// this.channels$ = of ( channels );
// this.showChannels = !!channels.length;
// this.ref.markForCheck();
// } );
}
doSearch() {
console.log( 'search', this.searchValue );
this.store.dispatch( new fromStore.LoadChannels( this.searchValue ) );
}
推荐答案
使用 ngIf
as
语法
*ngIf="channels$ | async as channels"
这篇关于由于ngIf语句,存储选择未运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!