首页 > 解决方案 > 如何捕获 API 调用的进度并使用自定义文本消息在 MAT-Progress 栏中显示?

问题描述

道歉,如果有人已经问过同样的问题。

谢谢。

聊天服务.ts

initiateDemoRequest(clientReqId): Observable < any > {
    return this.httpClient.post('https://my-endpoint-goes-here',
        clientReqId,
        {
            reportProgress: true,
            observe: 'events'
        }).pipe(catchError(this.handleError));

}

createRequest.component.ts

indicator = 0;
progress = 0;

this.myservice.initiateDemoRequest(clientReqId).subscribe( data => {
    if (data.type === HttpEventType.Sent) { // am assuming SENT is used to when api call started requesting to server
        this.progress += Math.round(100 * data.loaded / data.total);
        console.log('what is progerss', this.progress);
      } else  if (data.type === HttpEventType.Response) { // am assuming rESPONSE is used to when getting reponse from server        
        this.progress += Math.round(100 * data.loaded / data.total);
        console.log('this.progress', this.progress);
      }

      // window.open('https://trying-to-open-url-in-another-page.com', '_blank')
});


<mat-progress-bar mode="determinate" *ngIf="indicator"  value="indicator"></mat-progress-bar>

观看YouTube视频后使用拦截器的另一种尝试

创建加载器服务和拦截器,如下所示

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class LoaderService {
  public isLoading: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false) ;
  constructor() { }
}

拦截器.ts

constructor(public loaderService: LoaderService) { }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          console.log('event ?', event.type);
        }
        return event;
      }),
    );
  }

<mat-progress-bar *ngIf="loaderService.isLoading | async" mode="determinate" value="connectionProgress"></mat-progress-bar>

注意:我在上面的实现中没有看到任何错误。但我不知道如何捕获 http 的事件并记录它。

我想实现什么?

我想显示带有自定义消息的进度条,如下所示

它是如何发生的?

我有一个表,每行都有触发弹出窗口的选项connectWithRepresentative() (这里没有问题可以触发弹出窗口)

显示connect按钮以启动我的请求。这需要一些时间。在此期间,尝试向客户显示上述消息,以确保他们都准备好聊天,否则会出现错误消息。

很抱歉没有分享最小的可重现stackblitz代码。目前无法访问 plunker。stackblitz 出于某种原因。不知道为什么。

需要你们的帮助。

标签: javascriptangulartypescriptangular-material

解决方案


推荐阅读