如何从其中一个对象内部更新BehaviorSubject <object []>?

时间:2018-07-24 22:58:05

标签: typescript firebase google-cloud-firestore angular6 rxjs6

我正在尝试使用rxjs 6和firebase存储创建多文件上传器。

目标是多播此内容,以便用户无论在什么页面上都可以看到当前正在上传的内容。因此,我创建了以下课程。

//file.model.ts
import { Observable } from "rxjs";

export class FileUpload{
    id: string;
    size: string;
    file: File;
    path: string;
    databaseLocation: string;
    snapshot: Observable<firebase.storage.UploadTaskSnapshot>;
    percentage: Observable<number>;
    fileName: string;
    fileDescription: string;
    fileRef: string;
    downloadUrl: string;
    createdBy: string;
    dateCreated: string;
}

然后我创建了此服务。

import { Injectable } from "@angular/core";
import { AngularFirestore } from "angularfire2/firestore";
import { AngularFireStorage } from "angularfire2/storage";
import { FileUpload } from "models/file.model";
import { Observable, BehaviorSubject } from "rxjs";
import { tap, map, take } from "rxjs/operators";

@Injectable()
export class UploadFileService {

  private uploads$: BehaviorSubject<FileUpload[]>;

  constructor(private storage: AngularFireStorage,  private afs: AngularFirestore, private fleetService:FleetService) {
    this.uploads$ = new BehaviorSubject(new Array<FileUpload>());
    this.uploadFiles();
   }
}

这是uploadFiles函数

uploadFiles(){
    this.uploads$.subscribe(uploads=>{
        uploads.forEach(upload=>{
          if(!upload.snapshot){
            let task = this.storage.upload(upload.path, upload.file, { });
            console.log("Uploading new file");
            upload.fileName = upload.file.name;
            upload.snapshot = task.snapshotChanges();
            upload.percentage = task.percentageChanges();
            upload.snapshot.subscribe(
              snap => {
                if (snap.bytesTransferred === snap.totalBytes) {
                  console.log("deleting this file");

                }
              }
            )
          }
        })
    })
  }

这是更新BehaviorSubject的功能

pushUpload(files: FileList, uploadLocation: string) {
    Array.from(files).forEach(file => {
      let newFile = new FileUpload();
      newFile.file = file;
      newFile.path = `${uploadLocation}${new Date().getTime()}_${file.name}`;
      let uploads = this.uploads$.getValue();
      uploads.push(newFile);
      this.uploads$.next(uploads);

    });
  }

因此,页脚组件将订阅服务中的uploads $ BehaviorSubject并显示当前正在上传的文件。一旦完成,我想显示我已经完成的工作。但是然后我要根据阵列中有多少文件,在5-10秒后将它们删除。我知道从foreach循环中删除对象是不安全的。我该怎么做呢?

0 个答案:

没有答案