繁体   English   中英

在Angular App中收到多个值时,仅发出一个POST请求

[英]Making Just One POST Request When Multiple Values Are Received in Angular App

在我的Angular应用程序中,我遇到了这样一种情况,我正在通过事件发射器将用户选择的过滤器值从一个组件传递到另一个组件。 问题是,不是发送带有这些过滤器值的POST请求,而是发送/接收已发送的FOR EACH值的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()函数通过事件发射器接收的发射值的FOR EACH,即使请求的细节没有更改。 我该如何更改它以仅发出一个POST请求-而不是每次收到输入都会触发它?

我尝试制作onFilterReceived()和async函数,然后等待“选择”,如下所示:

public async onFilterReceived(value, type) {
    let selections = await this.filtersService.processByTypes(value, type);
    // other stuff

...但是,这里的问题当然是该函数中的其余步骤(包括API POST请求)将触发,而无需等待“选择”解决。 我该如何解决,所以我只发出一个POST请求?

我在这里对您的设计尚不完全清楚,但是在检测到更改之后是否需要等待一段时间才能重新过滤数据集?

这可以通过Debounce( https://davidwalsh.name/javascript-debounce-function )完成,这是处理POST请求中过滤器的传统方法,您希望在POST请求中根据输入的更改重新过滤。

本质上,您只是在限制函数调用的速度,这样,一旦第一个过滤器POST发生,您就会有一个窗口,可以在不触发另一个POST的情况下进行更改。

暂无
暂无

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

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