App中的API调用中处理发送两个参数

App中的API调用中处理发送两个参数

本文介绍了在Angular App中的API调用中处理发送两个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列过滤器功能,允许用户单击一系列过滤器,以过滤显示在网格视图中的数据.当我为每个过滤器使用单独的函数构建可观察对象时,这些过滤器就可以使用可观察对象工作.我们正在使用猫鼬内置的一种查询,使您可以按帖子的正文中的字段传递特定的查询.我这样使用它:

I have a series of filter functions that allow a user to click on a series of filters in order to filter data displaying in a grid view. I have the filters working using observables when I build them using an individual function for each filter. We are using a kind of query built into mongoose that lets you pass a specific query by field in the body of a post call. I am using it like this:

    onFilterReceived(language) {
        if (language) {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting",
                "languages.primary" : { $in: language },
                })
                .subscribe(resRecordsData => {
                    this.records = resRecordsData;
                    console.log('onFilterReceived: ' + language);
                },
                responseRecordsError => this.errorMsg = responseRecordsError);
        } else {
            this.filtersService.getByFilter(this.page, this.pagesize, {
                "services.workflow.status" : "consulting"
            })
                .subscribe(resRecordsData => {
                    this.records = resRecordsData;
                },
                responseRecordsError => this.errorMsg = responseRecordsError);
     }

在这里被调用的我的服务函数看起来像这样:

My service function, being called here, looks like this:

getByFilter(page, pagesize, body) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: this.headers });
    return this.http.post
    (`https://api.someurl.com/${this.ver}/customers/search?apikey=${this.key}&page=${page}&pagesize=${pagesize}`,
    body, options).map((res: Response) => res.json())
    .catch(this.filterErrorHandler);
}
    filterErrorHandler(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

这是按原样工作的.

但是,我想做的是处理传递多个键/值对,而不仅仅是一对.

However, what I want to be able to do is handle passing multiple key/value pairs, not just one.

您还会注意到,我正在检查是否仅运行请求 语言-也就是说,是否已通过过滤器单击发送了语言输入.这是必要的,因为否则,由于没有值,该函数在查询api时会出错.

You'll also notice that I am checking to only run the request if language exists - that is to say, if a language input has been sent via a filter click. This is necessary because otherwise the function errors out when querying the api because there is no value.

要一次处理两个过滤器,我尝试这样做:

To handle two filters at a time, I tried doing this:

onFilterReceived(language, nationality) {
    // Receive filter selections for language
    if (language) {
        this.filtersService.getByFilter(this.page, this.pagesize, {
            "services.workflow.status" : "consulting",
            "languages.primary" : { $in: language },
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
                console.log('onFilterReceived: ' + language);
            },
            responseRecordsError => this.errorMsg = responseRecordsError);
    }

    // Receive filter selections for nationality
    if (nationality) {
        this.filtersService.getByFilter(this.page, this.pagesize, {
            "services.workflow.status" : "consulting",
            "services.service" : { $in: nationality },
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
                console.log('onFilterReceived: ' + nationality);
            },
            responseRecordsError => this.errorMsg = responseRecordsError);
     }
}

但这没用.当我在上面传递两个字段/值时:

But this didn't work. While I am passing in two fields/values in the above:

        "languages.primary" : { $in: language },

在另一个:

        "services.service" : { $in: nationality },

...该功能无法正常运行.

... the function doesn't work properly.

为澄清起见,如果单击了语言"过滤器,我想在语言"上发送请求.但是,如果单击国籍"过滤器,我想发送有关国籍"的请求.

To clarify, if the "language" filter is clicked, I want to send the request on "language". But if the "nationality" filter is clicked, I want to send the request on "nationality".

但是我也不想失去一个参数来换取另一个参数.换句话说,如果在语言"过滤器上单击西班牙语",则希望它粘贴".然后,当从国籍"过滤器中单击美国"时,我希望请求同时通过这些参数进行过滤,而不是为了交换另一个而丢失一个.我该如何重新处理此功能以处理此问题?

But I also want to not lose one parameter in exchange for the other. In other words, if "spanish" is clicked on the "language" filter, I want that to "stick". Then when "American" is clicked from the "nationality" filter, I want the request to filter by BOTH of those parameters, not lose one in exchange for the other. How could I re-work this function to handle this?

顺便说一句,事件/值是通过Output()和EventEmitter()从另一个组件接收的.该视图如下所示:

By the way, events/values are being received from another component via Output() and EventEmitter(). The view looks like this:

        <list [records]="records"
            (sendLanguage)="onFilterReceived($event)"
            (sendNationality)="onFilterReceived($event)">
        </list>

我的过滤器的html如下所示:

And the html for my filters looks like this:

       <filter-option name="Language"
                        placeholder="Select Language"
                        [usePlaceholder]="!languageFilters.text"
                        [visible]="languageFilters.enabled">
            <filter-label>{{languageFilters.text}}</filter-label>
            <filter-menu>
                <div class="visit-type-filter-options">
                    <md-checkbox *ngFor="let option of languageFilters.options" [(ngModel)]="option.value">
                        {{option.language}}
                    </md-checkbox>
                </div>
            </filter-menu>
        </filter-option>

        <!--NATIONALITY-->
        <filter-option name="Nationality"
                        placeholder="Select Nationality"
                        [usePlaceholder]="!nationalityFilters.text"
                        [visible]="nationalityFilters.enabled">
            <filter-label>{{nationalityFilters.text}}</filter-label>
            <filter-menu>
                <div class="visit-type-filter-options">
                    <md-checkbox *ngFor="let option of nationalityFilters.options" [(ngModel)]="option.value">
                        {{option.nationality}}
                    </md-checkbox>
                </div>
            </filter-menu>
        </filter-option>

推荐答案

使代码整洁.这将处理多个参数.

To make the code neat. This will handle multiple parameters.

onFilterReceived(para: any, type: string) {
    let body:any = {};
    body['services.workflow.status'] = 'consulting';
    if (type == 'lan')
        body['languages.primary'] =  { $in: para };
    if (type == 'nat')
        body['services.service'] =  { $in: para };

    this.filtersService.getByFilter(this.page, this.pagesize, body)
        .subscribe(resRecordsData => {
                       this.records = resRecordsData;
                   },
                   responseRecordsError => this.errorMsg = responseRecordsError
        );
}

在模板中:

<list [records]="records"
    (sendLanguage)="onFilterReceived($event, 'lan')"
    (sendNationality)="onFilterReceived($event, 'nat')">
</list>

这篇关于在Angular App中的API调用中处理发送两个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:45