将角度材料进度栏链接到可观察值

时间:2018-12-06 16:17:12

标签: angular rxjs angular-material observable

我正在尝试将进度条链接到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);
    });
  }
}

我不太确定这是否与范围有关。

1 个答案:

答案 0 :(得分:2)

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

@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)
  );
}