Angular 5+:如何延迟/所有HttpClient请求?

Wol*_*359 12 rxjs angular

我有这个代码:

this.loading = true;
this.http.get<IUser[]>(Urls.users())
            .subscribe(
                response => {
                    this._values = <IUser[]>response;
                    this.root.next({'users': this._values});
                },
                e => console.log(e),
                () => this.loading = false
            );
Run Code Online (Sandbox Code Playgroud)

调用此代码的页面有一个微调器,当'loading'设置为'true'时显示.但是当请求以0.5秒完成时,微调器几乎没有显示,并且在页面上看起来很奇怪.

如何在完成之前等待1秒(不使用setTimeout())?

有没有办法延迟所有的http请求,而不必像上面的代码那样修改每个代码?

Phi*_*hil 23

使用rxjs/delay:

this.http.get(...).delay(500).subscribe(...);
Run Code Online (Sandbox Code Playgroud)

在Angular 6+中:

this.http.get(...).pipe(delay(500)).subscribe(...);
Run Code Online (Sandbox Code Playgroud)

  • @Karan如果您使用的是Angular 6+,则必须使用管道:`this.http.get(...)。pipe(delay(500))。subscribe(...)` (3认同)

Wol*_*359 5

我最终使用了 HttpInterceptor + 延迟运算符(感谢 @Faisal):这是我的问题的解决方案,但不一定是最好的用户体验。请参阅@AlexanderLeonov 对此的评论。

// ANGULAR
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';

// OBSERVABLES
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/delay';

@Injectable()
export class DelayInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(request);
        return next.handle(request).delay(500);
    }
}
Run Code Online (Sandbox Code Playgroud)


Adi*_*yaj 3

对于最新版本的 Angular,您可以使用:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { delay } from 'rxjs/operators';

@Injectable()
export class DelayInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(request);
    return next.handle(request).pipe(delay(5000));
  }
}
Run Code Online (Sandbox Code Playgroud)

参考:Wolf359 答案