【问题标题】:Angular Promise - debounceTime behaviorAngular Promise - debounceTime 行为
【发布时间】:2020-01-03 09:51:42
【问题描述】:

我正在使用 Angular 7,并且我有以下(工作)代码。

    import { Http } from '@angular/http';


    public httpService: Http;
    (....)

    public callAction(): Promise<void> {
        let r = this.httpService.post(url, panelData);

        return r.toPromise().then((response: { json: () => any; }) => {
            if (response.json()) {
                this.processResponse(panel, response.json());
            }
        }).catch((reason: any) => {
            throw reason;
        });
    }

方法this.httpService.post返回一个Observable

我正在尝试避免多次服务器调用,为此我正在尝试使用debounce behavior

我在我的 Observable 上添加了 debounceTime,但是当调用 Promise 时它不起作用。

let r = this.httpService.post(url, panelData).debounceTime(5000);
return r.toPromise().then()

我知道我没有订阅 Observable,但是当我调用 toPromise() 时,应该将此行为“导入”到 promise 中吗?

PS- 我也尝试使用管道

let r = this.httpService.post(url, panelData).pipe(debounceTime(5000));

【问题讨论】:

  • 您必须按照链接中的说明将 debounce 运算符用于 pipe()。
  • 我用管道进行了测试,但仍然无法正常工作 -> let r = this.httpService.post(url, panelData).pipe(debounceTime(5000));
  • 您使用的是哪个角度版本? v5?
  • 我正在使用 Angular v7

标签: angular angular-promise debounce


【解决方案1】:

您需要在 callAction() 函数之外拥有 let r = this.httpService.post(url, panelData).debounceTime(5000);,而是作为类的单独函数/属性。 发生的情况是每次调用 callAction() 函数时都会创建一个新的 debounce observable r,而不是每次都需要调用同一个:

import { Http } from '@angular/http';


public httpService: Http;
(....)

let r = this.httpService.post(url, panelData).debounceTime(5000);

public callAction(): Promise<void> {
    return this.r.toPromise().then((response: { json: () => any; }) => {
        if (response.json()) {
            this.processResponse(panel, response.json());
        }
    }).catch((reason: any) => {
        throw reason;
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2017-12-27
    • 2021-10-10
    • 2022-01-19
    • 2018-10-15
    相关资源
    最近更新 更多