在Angular App中的Obseable POST请求中使用switchMap

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Angular App中的Obseable POST请求中使用switchMap相关的知识,希望对你有一定的参考价值。

在我的Angular应用程序中,我有一个函数,它接受各种用户选择的过滤器值,并相应地返回数据。这些值通过事件发送器传递给函数,事件发送器将值从一个组件传递到另一个组件,如下所示:

<data-list [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-list>

然后,我接受这些值,处理它们,然后向API发送POST请求以获取返回的过滤数据:

public onFilterReceived(value, type)
{
    let selections = this.filtersService.processByTypes(value, type);

    this.route.params.subscribe(
        (params: any) => {
            this.page = params['page'];
        }
    );

    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);
}

这里调用的filterService函数如下所示:

filters = { language: [], location: [], zipcode: [], firstName: [], lastName: [], branch: [] };

public processByTypes(value, type) {
  if (value && type) { this.filters[type] = value; }
  return this.filters;
}

public getByFilters(page, pagesize, language?, location?, zipcode?, firstName?, lastName?, branch?, fn?: any) {
    return this.apiService.post({
      req: this.strReq, reqArgs: { page, pagesize, stage, language, location, zipcode, firstName, lastName, branch }, callback: fn });
}

这里调用的API POST函数如下所示:

public post(params: {
    req: string,
    reqArgs?: any,
    reqBody?: any,
    callback?: IRequestCallback
}): Observable<Response>
{
    params['reqType'] = 'post';

    return this.runHttpRequest(params);
}

我遇到的问题是,每次onFilterReceived()函数接收到过滤器值时,它都会导致POST请求触发,因此我最终会得到7或8个POST请求,基本上没有更改过滤器值。所以我想要做的是收集这些值,只发出一个POST请求。

现在POST请求返回一个observable,所以我的想法是我应该能够使用像switchMap这样的操作来处理它。这听起来有用吗?这是一个问题。第二个问题是关于正确的语法。

我尝试将switchMap链接到POST请求的末尾,如下所示:

public getByFilters(page, pagesize, stage?, language?, location?, zipcode?, firstName?, lastName?, branch?, fn?: any) {
    return this.apiService.post({
      req: this.strReq, reqArgs: { page, pagesize, stage, language, location, zipcode, firstName, lastName, branch }, callback: fn }).switchMap;
}

......但那没用。没有错误,但它没有用,因为我仍然看到多个POST请求消失。

我正确理解switchMap吗?如果我想将它链接到我的POST请求操作,那么语法需要什么?

答案

我将尝试编写一个简化的示例,您希望从中获得这个想法。你应该有一个过滤器当前状态的主题。 SwitchMap到api调用,你可以抛出debounceTime给用户时间连续快速更改。

要使用较新的可管道运算符。

filter$:Subject<any> = new Subject();
data:any;
destroy$:Subject<void> = new Subject();

ngOnInit() {
    this.filter$.pipe(
        takeUntil(destroy$), // stop and cleanup when component gone
        debounceTime(400),
        switchMap(filter => this.service.post(filter)) // switch one stream to another
    ).subscribe(data => this.data = data)
}

onFilterReceived(value, type)
{
    let selections = this.filtersService.processByTypes(value, type);
    this.filter$.next(selections);
}

ngOnDestroy() { this.destroy$.next() }

以上是关于在Angular App中的Obseable POST请求中使用switchMap的主要内容,如果未能解决你的问题,请参考以下文章

Angular 2+,有啥方法可以声明一个模块中的所有组件,然后在 app.module.ts 中导入?

Angular 9在不在app(默认)文件夹中的特定文件夹中创建组件

Appium基于Python APP自动化测试框架 -- PO

RESTful Crud MEAN.js 路由

Angular 5 中的页眉和页脚

Angular 中的环境导入