【发布时间】:2021-05-25 18:48:13
【问题描述】:
我在一个 Angular 组件中有两个主题,它们利用同一组可管道运算符为两个不同的表单字段提供预先输入的搜索查找。示例:
this.codeSearchResults$ = this.codeInput$
.pipe(
untilDestroyed(this),
distinctUntilChanged(),
debounceTime(250),
filter(value => value !== null),
switchMap((value: string) => {
const params: IUMLSConceptSearchParams = {
...TERMINOLOGY_SEARCH_PARAMS,
sabs: this.sabs,
term: value
};
return this.terminologyService.umlsConceptSearch(params);
}),
);
definition for pipe 似乎可以接受任意数量的函数,但通过 spread 提供函数
this.codeSearchResults$ = this.codeInput$.pipe(...operators);
没有按预期工作。如何为两个 Subject 提供单一输入函数源以保持我的代码 DRY?
编辑
按照 Dan Kreiger 的回答中的选项 #2,我的最终代码如下:
const operations = (context) => pipe(
untilDestroyed(context),
distinctUntilChanged(),
debounceTime(250),
filter(value => value !== null),
switchMap(value => {
const term: string = value as unknown as string;
const params: IUMLSConceptSearchParams = {
...TERMINOLOGY_SEARCH_PARAMS,
sabs: context.sabs,
term,
};
return context.terminologyService.umlsConceptSearch(params) as IUMLSResult[];
}),
);
this.codeSearchResults$ = this.codeInput$
.pipe(
tap(() => this.codeLookupLoading = true),
operations(this),
tap(() => this.codeLookupLoading = false),
) as Observable<IUMLSResult[]>;
this.displaySearchResults$ = this.displayInput$
.pipe(
tap(() => this.displayLookupLoading = true),
operations(this),
tap(() => this.displayLookupLoading = false),
) as Observable<IUMLSResult[]>;
我需要编写几个 tap() 函数,它们对每个主题都是唯一的,并且可以按预期工作。
【问题讨论】:
标签: rxjs