我试图在我的 http 调用中放置一个进度条,但有些我无法发出同步 HTTP 调用请求,而是以异步方式进行。
下面是调用http的函数
public authenticationt2cHTTP(email, password) {
console.log("authenticationt2cHTTP WITH HEADERS");
const body = new HttpParams()
.set('email', email)
.set('password', password);
const req = new HttpRequest('POST', 'http://192.168.0.135:8080/rest/auth/login', body, {
reportProgress: true,
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
});
this.http.request(req).subscribe(event => {
// Via this API, you get access to the raw event stream.
// Look for upload progress events.
if (event.type === HttpEventType.UploadProgress) {
// This is an upload progress event. Compute and show the % done:
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% uploaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely uploaded!');
}
});
}
下面是我在组件类中用于调用的代码,showload 是用于显示/隐藏页面预加载器的临时变量。
this.showLoader = false;
var k = this.myhttpService.authenticationt2c(this.form.get("email").value, this.form.get("password").value);
this.showLoader = true;
最佳答案
如评论中所述,这是异步的,因此虽然请求需要一些时间来执行,
this.showLoader = false;
// takes some time to execute
var k = this.myhttpService.authenticationt2c(...);
// executed while waiting for above code to execute
this.showLoader = true;
相反,从您的服务返回一个 Observable 并在组件中订阅。然后在回调(订阅)中切换 bool 标志。我猜想在请求完成后,您实际上希望将 bool 标志 showLoader
切换为 false
,因此我在下面切换了它们:
this.showLoader = true;
this.myhttpService.authenticationt2c(...)
.subscribe(() => this.showLoader = false)
并且从服务,如前所述,返回一个 Observable,所以使用 map
而不是 subscribe
:
this.http.request(req).map(event => { ... })
检查这些链接以了解异步性:How do I return the response from an Observable/http/async call in angular2?和 How do I return the response from an asynchronous call?
关于angular - 如何跟踪 Angular HTTP POST 调用进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113451/