简体   繁体   English

如何重用代码并使其更灵活?

[英]How to reuse code and make it more flexible?

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.此代码侦听来自过滤器filtersChanges的更改,并将它们的最新值作为数组返回。

Then array is handled by FilterUrlCombiner and FilterUrlBuilder as finish result I get string URL in this.filterBy with all parameters from array.然后数组由FilterUrlCombinerFilterUrlBuilder处理,作为完成结果,我在this.filterBy中得到字符串 URL,其中包含数组中的所有参数。

I need to reuse the code wrapped in subscribe() in another place, but I dont want copy/past.我需要在另一个地方重用subscribe()中包含的代码,但我不想复制/过去。 How to reuse code and make it more flexible?如何重用代码并使其更灵活?

You're essentially passing callback functions to next and error parameters of the subscription.您实际上是将回调函数传递给订阅的nexterror参数。 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.您需要使用bind() function 来传递this关键字的含义来指向class 成员变量。 More info here on how to access this keyword in callbacks.有关如何this关键字的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM