gpt4 book ai didi

Angular 2+ HTTP 请求 - 显示成功和错误响应的最短持续时间的加载微调器

转载 作者:行者123 更新时间:2023-12-04 09:37:59 25 4
gpt4 key购买 nike

需求 :

每次出现 时,我都需要在 UI 上显示加载微调器具体 发出 HTTP 请求。

为了有一个漂亮的视觉方面,我决定在屏幕上显示微调器 至少 1 秒 ,即使请求持续时间较短(实际上,它持续 0.1 秒到 3-4 分钟之间,所以最好保持微调器至少 1 秒)。所以,条件是:

  • 如果请求需要 超过 1 秒,微调器将显示 1 秒
  • 如果请求需要 更长 超过 1 秒,微调器将显示直到完成。

  • 我知道这种方法从 UI/UX 的 Angular 是值得商榷的 - 但我更愿意将其视为技术挑战。

    我试过的代码:

    正如在 SO 上的其他实现中发现的那样,我尝试了一种方法 combineLatest - 结合一个需要 1s 的 Observable 和 http 请求的 Observable。

    load() {
    this.loading = true; // this will show the spinner
    combineLatest(timer(1000), this.service.apiCall())
    .pipe(
    finalize(()=> {
    this.loading = false; // this will hide the spinner
    }),
    map(x => x[1])
    )
    .subscribe(x => {
    console.log(x);
    });
    }

    如果 HTTP 请求以状态 200 返回,这很有效。

    问题:

    如果 HTTP 请求返回错误 (4/5xx),则上述代码不起作用。
    Observables 在 HTTP 请求结束后立即结束。

    即使请求首先完成,但出现错误,我也希望微调器具有相同的行为。

    我做了一个简单的 Stackblitz,我们可以在其中处理不同的请求:
    https://stackblitz.com/edit/spinner-with-min-duration-zcp7hc

    谢谢!

    最佳答案

    来自 rxjs文档:

    If at least one Observable was passed to combineLatest and all passed Observables emitted something, resulting Observable will complete when all combined streams complete. ... On the other hand, if any Observable errors, combineLatest will error immediately as well, and all other Observables will be unsubscribed.



    因此,您必须使用 catchError 使用自己的错误捕获例程来处理导致 observable 的错误。管道,因此它不会向 combineLatest 抛出错误运算符(operator)。像这样的事情会起作用。
    load() {
    this.loading = true; // this will show the spinner
    combineLatest(timer(1000),
    this.service.apiCall().pipe(
    catchError(err)=>{
    return of(err); // Return observable wrapped with error.
    }))
    .pipe(
    finalize(()=> {
    this.loading = false; // this will hide the spinner
    }),
    map(x => x[1])
    )
    .subscribe(x => {
    console.log(x);
    //Check in the result if there is an error in http
    if(x instanceof HttpErrorResponse) {
    // do what you want in error scenario.
    }
    });
    }

    Stackblitz 演示:
    https://stackblitz.com/edit/spinner-with-min-duration-ls9dq7

    关于Angular 2+ HTTP 请求 - 显示成功和错误响应的最短持续时间的加载微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62466280/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com