【问题标题】:Linking Angular Material Progress bar to Observable value将 Angular Material Progress 条链接到 Observable 值
【发布时间】:2018-12-06 16:17:12
【问题描述】:

我正在尝试将进度条链接到 HTTP POST 事件。这样我就可以向我的用户显示上传进度。我目前有这个:

@Component({
  selector: 'app-upload-progress-snackbar',
  template: `<mat-progress-bar mode="determinate" [value]="progress"></mat-progress-bar>`,
  styles: [],
})
export class UploadProgressComponent implements OnInit {
  constructor(@Inject(MAT_SNACK_BAR_DATA) public data) { }

  public UploadObservable;

  public progress = 0;
  ngOnInit() {
    this.UploadObservable = this.data.uploadProgress;

    this.UploadObservable.subscribe((event) => {
      // Don't change value after finished upload
      if (event.loaded !== undefined) {
        // Convert progress to percentage and integer
        this.progress = Math.trunc(event.loaded / (event.total || event.loaded) * 100);

        this.progress.valueOf();
      }
      // Log upload progress
      console.log(this.progress);
    });
  }
}

我不太确定它是否与范围或其他有关。

【问题讨论】:

    标签: angular rxjs angular-material observable


    【解决方案1】:

    您应该使用异步管道直接从组件内订阅:

    @Component({
      selector: 'app-upload-progress-snackbar',
      template: `<mat-progress-bar mode="determinate" [value]="progress | async"></mat-progress-bar>`,
      styles: [],
    })
    export class UploadProgressComponent implements OnInit {
      constructor(@Inject(MAT_SNACK_BAR_DATA) public data) { }
    
      public progress = this.data.uploadProgress.pipe(
        map(({ loaded, total }) => loaded ? Math.round(loaded / (total || loaded) * 100) : 0)
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2020-10-08
      相关资源
      最近更新 更多