In my application, I have two comboboxes in a component.
Their default values are both null
.
When selecting a period or a user, the value is sent to the store. This allows you to use the period and the selected user in different components.
Combobox.component TO Store:
onSelectedWalletsPeriod(period: Period) {
this.store.setSelectedWalletsPeriod(period);
}
onSelectedWalletsUser(user: User) {
this.store.setSelectedWalletsUser(user);
}
Store:
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);
}
}
Store TO 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);
}
}
To display the list of the second component, I have to select a period AND a user. Until then everything works perfectly.
But what I would like to do is execute a function when a user AND a period are selected. This function would also execute when changing the value of one of the two comboboxes.
This function will allow me to retrieve a wallet list from my database based on the period and the user.
I do not know how to do it. If you have an idea, I'm interested.
Here is a small example: Stackblitz HERE
Thank you in advance.
You can use combineLatest
to listen for the latest value of either select and then filter those value where not both values are set:
combineLatest(this.store.selectedWalletsPeriod$, this.store.selectedWalletsUser$)
.pipe(filter(([period, user]) => period && user))
.subscribe(([period, user]) => console.log('period=' + period + ',user=' + user));
The example above should log a value as soon as both values are set.
See also: documentation for combineLatest