Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何创建默认为值的可观察对象(即使它从未完成)_Angular_Rxjs - Fatal编程技术网

Angular 如何创建默认为值的可观察对象(即使它从未完成)

Angular 如何创建默认为值的可观察对象(即使它从未完成),angular,rxjs,Angular,Rxjs,有没有一种方法可以使一个可观察的对象既从空数组开始,又默认为空数组(如果它没有通过过滤器) 这就是我的工作 inactiveItems$: Observable<any[]> = combineLatest(this.store.select(fromAuth.getAuthState), this.showInactiveItems$).pipe( filter(([authState, showInactiveItems]: any) => authState?.rol

有没有一种方法可以使一个可观察的对象既从空数组开始,又默认为空数组(如果它没有通过过滤器)

这就是我的工作

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([])
);
inactiveItems$:Observable=CombineTest(this.store.select(fromAuth.getAuthState),this.showInactiveItems$).pipe(
筛选器(([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')。管道(
catchError(err=>of([]))
)),
startWith([]))
);
一些解释:

1) showInactiveItems是一个布尔行为主题

2) authstate来自NgRx存储

3) 从开关图中可以观察到的是AngularFire

我尝试过使用defaultIfEmpty操作符,但它只在可观察对象完成时工作,或者通过添加类似take(1)的方式工作,但是对于来自AngularFire的可观察对象,它需要保持打开状态,以便在进行更改时,它们将在应用程序中更新


我也尝试过搞乱IIF创建操作符,但我不知道如何在条件改变时再次运行observable。如果条件不匹配,filter将停止流。相反,您应该使用
map
返回一个值,该值确定
switchMap
是运行还是返回空数组

inactiveItems$:可观察=组合测试(
this.store.select(fromAuth.getAuthState),
这是一个虚拟项目$
).烟斗(
映射(([authState,showInactiveItems]:any)=>{
if(authState?.roles?.isAgent==true&&showInactiveItems==true){
返回authState.uid;
}
返回null;
}),
开关映射(uid=>this.getItems(uid))
);
私有getItems(uid):可观察{
如果(!uid){
归还([]);
}
返回此.db.collection('items',ref=>
ref.where('agentId','=',uid)
.where('active','=',false)
).valueChanges({idField:'id'}).pipe(
catchError(err=>of([]))
);
}
map
如果
过滤器中的条件匹配,则返回
uid
,否则返回
null


switchMap
如果
uid
为false,则返回一个空数组,否则将获取项目。

我认为您需要的是一个行为主体。我目前正在使用一个行为主体作为showInactiveItems布尔值,每当用户在ui上切换开关时,都会调用.next()