在我的Angular应用程序中,我遇到的情况是我通过事件发射器将用户选择的过滤器值从一个组件传递到另一个组件。问题是,不是发送一个带有这些过滤器值的POST请求,而是发出一个POST请求,用于发出/接收的每个值。我需要做的是弄清楚如何收集这些值,然后只发送一个POST请求。
在我的接收组件的视图中,我将获取这些发出的事件值,并将它们传递给onFiltersReceived()函数,如下所示:
<data-view [records]="records"
(sendLocation)="onFilterReceived($event, type = 'location')"
(sendZipcode)="onFilterReceived($event, type = 'zipcode')"
(sendFirstName)="onFilterReceived($event, type = 'firstName')"
(sendLastName)="onFilterReceived($event, type = 'lastName')"
(sendLanguage)="onFilterReceived($event, type = 'language')"
(sendBranch)="onFilterReceived($event, type = 'branch')">
</data-view>
然后我根据过滤器值中传递的API发送API请求进行过滤,如下所示:
public onFilterReceived(value, type) {
let selections = this.filtersService.processByTypes(value, type);
let fn = resRecordsData => {
this.records = resRecordsData;
let data = resRecordsData.data;
};
this.filtersService.getByFilters(
this.page - 1, this.pagesize, this.language = selections.language, this.location = selections.location,
this.zipcode = selections.zipcode, this.firstName = selections.firstName, this.lastName = selections.lastName,
this.branch = selections.branch, fn);
}
&#34; filtersService&#34;这里引用的服务层函数如下所示。首先,处理传入过滤器的函数:
filters = { language: [], location: [], zipcode: [], firstName: [], lastName: [], branch: [] };
public processByTypes(value, type) {
if (value && type) { this.filters[type] = value; }
return this.filters;
}
然后通过网络发送的API POST请求:
public getByFilters(page, pagesize, language?, location?, zipcode?, firstName?, lastName?, branch?, fn?: any)
{
return this.apiService.post({
req: this.strReq, reqArgs: { page, pagesize, language, location, zipcode, firstName, lastName, branch }, callback: fn });
}
同样,正如我所说,这是有效的 - 但是效率低,因为POST请求通过onFilterReceived()函数触发通过事件发射器获取的每个发射值,即使请求的详细信息没有出现。改变了。如何更改此选项以仅生成一个POST请求 - 而不是每次收到输入时都触发它?
我尝试制作onFilterReceived()和异步函数,并等待&#34;选择&#34;,如下所示:
public async onFilterReceived(value, type) {
let selections = await this.filtersService.processByTypes(value, type);
// other stuff
...但当然这里的问题是该函数中的其余步骤(包括API POST请求)将触发,而不等待&#34;选择&#34;解决。我如何解决这个问题,以便我只发出一个POST请求?
答案 0 :(得分:0)
我在这里的设计并不完全清楚,但在重新选择数据集选项之前检测到更改后会等待一段时间吗?
这可以通过Debounce(https://davidwalsh.name/javascript-debounce-function)完成,并且是通过POST请求处理过滤器的传统方式,您希望对输入的更改进行重新过滤。
基本上你只是限制你的函数调用,这样一旦第一个过滤器POST发生,你就有了一个窗口,你可以在不触发另一个POST的情况下进行更改。