我有这段代码:
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
);
调用此代码的页面有一个微调器,显示何时加载&#39;设置为&#39; true&#39;。但是当请求在0.5秒内完成时,微调器几乎没有显示,并且在页面上看起来很奇怪。
如何在完成之前等待1秒(不使用setTimeout())?
有没有办法延迟所有的http请求,而不必像上面的代码那样修改每个代码?
答案 0 :(得分:16)
使用rxjs / delay:
this.http.get(...).delay(500).subscribe(...);
在Angular 6 +中:
this.http.get(...).pipe(delay(500)).subscribe(...);
答案 1 :(得分:2)
我最终使用了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);
}
}
答案 2 :(得分:-1)
this.loading = true;
const timer = Observable.timer(500); //500 miliseconds
timer.subscribe(t => {
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
);
});