I have the follwing code:
combineLatest(...this.filtersList.map((f) => f.filtersChanges)).subscribe(
(selectedFilters: Filter[]) => {
const filterUrlCombiner = new FilterUrlCombiner();
const filterUrlBuilders = selectedFilters
.filter(Boolean)
.map((filter) => new FilterUrlBuilder(filter, ComparingOperation.eq));
const filterUrls = filterUrlBuilders.map((filter) => filter.buildStringUrl()).filter(Boolean);
this.filterBy = filterUrlCombiner.combineUrl(filterUrls);
this.settingsService.setExecutionFiltersSettings(selectedFilters);
},
(error) => {
console.log('ERROR: ' + error);
},
);
This code listens changes from filters filtersChanges
and returns them latest values as array.
Then array is handled by FilterUrlCombiner
and FilterUrlBuilder
as finish result I get string URL in this.filterBy
with all parameters from array.
I need to reuse the code wrapped in subscribe()
in another place, but I dont want copy/past. How to reuse code and make it more flexible?
You're essentially passing callback functions to next
and error
parameters of the subscription. You could define the callbacks separately and invoke them from the subscription.
combineLatest(...this.filtersList.map((f) => f.filtersChanges)).subscribe(
this.onNext.bind(this),
this.onError.bind(this)
);
onNext(selectedFilters: Filter[]) {
const filterUrlCombiner = new FilterUrlCombiner();
const filterUrlBuilders = selectedFilters
.filter(Boolean)
.map((filter) => new FilterUrlBuilder(filter, ComparingOperation.eq));
const filterUrls = filterUrlBuilders.map((filter) => filter.buildStringUrl()).filter(Boolean);
this.filterBy = filterUrlCombiner.combineUrl(filterUrls);
this.settingsService.setExecutionFiltersSettings(selectedFilters);
}
onError(error: any) {
console.log('ERROR: ' + error);
}
You need to use the bind()
function to pass in the meaning of this
keyword to point to the class member variables. More info here on how to access this
keyword in callbacks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.