在我的应用程序中,我在一个组件中有两个组合框。它们的默认值都是null
。
选择期间或用户时,该值将发送到商店。这允许您在不同的组件中使用句点和所选用户。
Combobox.component TO Store:
onSelectedWalletsPeriod(period: Period) {
this.store.setSelectedWalletsPeriod(period);
}
onSelectedWalletsUser(user: User) {
this.store.setSelectedWalletsUser(user);
}
商店:
export class MystoreComponentStore {
private selectedWalletsPeriodSubject = new BehaviorSubject<Period>(null);
private selectedWalletsUserSubject = new BehaviorSubject<User>(null);
public selectedWalletsPeriod$ = this.selectedWalletsPeriodSubject.asObservable();
public selectedWalletsUser$ = this.selectedWalletsUserSubject.asObservable();
constructor() {}
setSelectedWalletsPeriod(period: Period) {
this.selectedWalletsPeriodSubject.next(period);
this.selectedWalletSubject.next(null);
/# DEBUG #/
console.log('selectedPeriod:', period);
}
setSelectedWalletsUser(user: User) {
this.selectedWalletsUserSubject.next(user);
this.selectedWalletSubject.next(null);
/# DEBUG #/
console.log('selectedUser:', user);
}
}
存储到Result.component:
export class ResultComponent implements AfterViewInit {
selectedWalletsPeriod: Period = null;
selectedWalletsUser: User = null;
constructor(public store: MystoreComponentStore) { }
ngAfterViewInit() {
this.store.selectedWalletsPeriod$.subscribe(period=> this.selectedWalletsPeriod = period);
this.store.selectedWalletsUser$.subscribe(user=> this.selectedWalletsUser = user);
}
}
要显示第二个组件的列表,我必须选择一个句点和一个用户。在此之前一切都很完美。
但我想要做的是在选择用户和句点时执行一个功能。当改变两个组合框之一的值时,也会执行该功能。
此功能允许我根据期间和用户从我的数据库中检索钱包列表。
我不知道怎么做。如果你有想法,我很感兴趣。
这是一个小例子:Stackblitz HERE
先感谢您。
你可以使用combineLatest
来监听select的最新值,然后过滤那些没有设置两个值的值:
combineLatest(this.store.selectedWalletsPeriod$, this.store.selectedWalletsUser$)
.pipe(filter(([period, user]) => period && user))
.subscribe(([period, user]) => console.log('period=' + period + ',user=' + user));
一旦设置了两个值,上面的示例就应该记录一个值。
你可以压缩你的观察者:
https://www.learnrxjs.io/operators/combination/zip.html
如果两个observable都获得了一个值,并且每次都有一个值发生变化,这将调用该订阅。但是你需要通过“not null”或类似的东西过滤你的observable,因为你用null初始化你的行为主题。
顺便说一句:你有没有试过redux或ngrx(有角度的redux)?您不需要实现自己的商店/操作处理/副作用/订阅逻辑。