如何跟踪 Angular HTTP POST 调用进度

Fer*_*qui 5 angular-cli angular

我试图在我的 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!');
      }
    });

  }
Run Code Online (Sandbox Code Playgroud)

下面是我在组件类中用于进行调用的代码,showload 是用于显示/隐藏页面预加载器的临时变量。

this.showLoader = false;
      var k = this.myhttpService.authenticationt2c(this.form.get("email").value, this.form.get("password").value);
      this.showLoader = true;
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 2

正如评论中提到的,这是异步的,因此虽然请求需要一些时间来执行,

this.showLoader = false;
// takes some time to execute
var k = this.myhttpService.authenticationt2c(...);
// executed while waiting for above code to execute
this.showLoader = true;
Run Code Online (Sandbox Code Playgroud)

相反,从您的服务中返回一个 Observable 并在组件中进行订阅。然后在回调(订阅)内切换布尔标志。我猜想您实际上希望在请求完成后将布尔标志切换到,所以我在下面切换了它们showLoaderfalse

this.showLoader = true;
this.myhttpService.authenticationt2c(...)
  .subscribe(() => this.showLoader = false)
Run Code Online (Sandbox Code Playgroud)

如上所述,从服务中返回一个 Observable,因此使用map而不是subscribe

this.http.request(req).map(event => { ... })
Run Code Online (Sandbox Code Playgroud)

检查这些链接以了解异步性:How do I return the response from an Observable/http/async call in angular2? 以及如何从异步调用返回响应?