angular - 如何跟踪 Angular HTTP POST 调用进度

标签 angular angular-cli

我试图在我的 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/

相关文章:

javascript - 我的 "this.router.navigate"在我的 Angular 2 应用程序中没有触发

node.js - 如何将 Angular cli 项目与 nodejs/expressjs 项目集成

angular-cli 更新未定义错误的 service-worker id

javascript - Uncaught ReferenceError : require is not defined on Angular 2 webpack global library installation

javascript - Angular 2在指向根路由器的子节点中添加routerLink

javascript - 如何检测用户是否切换了浏览器选项卡?

javascript - Angular [innerHTML] 无法正常工作

html - 进入 Modal 的 Ionic 3(单击)事件在 ios 中不起作用

javascript - 为什么在 Angular 项目中没有 Angular-CLI 为 'model' 生成命令?

javascript - 在 Ubuntu Zesty 17.04 上安装 Node 6.9