【发布时间】:2018-09-26 13:48:31
【问题描述】:
在我的 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 请求,根据传入的过滤器值进行过滤,如下所示:
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);
}
此处引用的“filtersService”服务层函数如下所示。一、处理传入过滤器的函数:
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() 和异步函数,并等待“选择”,如下所示:
public async onFilterReceived(value, type) {
let selections = await this.filtersService.processByTypes(value, type);
// other stuff
...但是这里的问题当然是函数中的其余步骤(包括 API POST 请求)将触发,而无需等待“选择”来解决。我该如何解决这个问题,以便我只发出一个 POST 请求?
【问题讨论】:
标签: javascript angular typescript post