値への観察可能なデフォルトを作成する方法(それが完了したことがない場合でも)

mattc19:

両方の空の配列から始めて、それがフィルターを通過していない場合も、空の配列がデフォルトになりますように観察をする方法はあります。

ここで私が働いているものです

inactiveItems$: Observable<any[]> = combineLatest(this.store.select(fromAuth.getAuthState), this.showInactiveItems$).pipe(
  filter(([authState, showInactiveItems]: any) => authState?.roles?.isAgent === true && showInactiveItems === true),
  switchMap(([authState, showInactiveItems]) => this.db.collection('items', ref => ref.where('agentId', '==', authState.uid).where('active', '==', false)).valueChanges({ idField: 'id' }).pipe(
    catchError(err => of([]))
  )),
  startWith([])
);

いくつかの説明:

1)showInactiveItemsブール動作の対象であります

2)authstateはNgRx店から来ています

3)switchMapから観察はAngularFireからです

私はdefaultIfEmpty演算子を使用してみましたが、ときに観察完了またはテイク(1)のように追加することによって、それだけで動作しますが、AngularFireから観測可能で、それは変更が加えられた場合、彼らはアプリに更新するように開いたままする必要があります。

私はまた、IIF作成演算子をいじり試みたが、私は状況が変わったときに再び観測可能な実行を作るためにどのように分かりませんでした。

クルト・ハミルトン:

filter条件が一致しない場合は、ストリームを停止します。代わりに、あなたが使用する必要があるmapかどうかを決定する値を返すためにswitchMap実行するか、空の配列を返します。

inactiveItems$: Observable<any[]> = combineLatest(
  this.store.select(fromAuth.getAuthState), 
  this.showInactiveItems$
).pipe(
  map(([authState, showInactiveItems]: any) => {
    if (authState?.roles?.isAgent === true && showInactiveItems === true) {
      return authState.uid;
    }

    return null;
  }),
  switchMap(uid => this.getItems(uid))
);

private getItems(uid): Observable<any[]> {
  if (!uid) {
    return of([]);
  }

  return this.db.collection('items', ref => 
    ref.where('agentId', '==', uid)
       .where('active', '==', false)
    ).valueChanges({ idField: 'id' }).pipe(
      catchError(err => of([]))
    );
}

map戻ってuidあなたが持っていたという条件であればfilter一致し、そうでない場合はリターンnull

switchMap場合は、空の配列を返すuidfalsyあり、そうでないアイテムを取得します。

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=377352&siteId=1