Handling returns from an Array <BehaviorSubject updating page after completing upload

0

If possible, I would like to hide the item after completing the upload and update the page view shortly after completion. I don’t want to use pull refresh to update, I want it to be automatic I must remember that on the same page I have another list that I would also like to be updated after each sending end, so I think it is easier to call ionViewWillEnter by updating the entire page but I don’t know how to do that.

Thus, when each upload is finished, the items in the sending list will disappear and the return list from the server will update.

If it is not possible, I would like to at least change the order of the returns of the Array <BehaviorSubject by placing the most recent in the first positions

Service:

private percent: Array<BehaviorSubject<{ id: string, aux: number, percent: string, name: string, date:string, savedId: string, status: number }>> = []

salvarMalote(payload){
    console.log(payload)
    
    var filePath = payload.imageURI;
    var filename = filePath.split("/").pop();
    var extencao = filename.split(".").pop();
    var paramsEnvio = {
      discClient: payload.discription, 
      code: this.client.code, 
      email:this.email, 
      nameFile: filename,
      chaveappmury: this.date 
    }
    let params = JSON.stringify(paramsEnvio)
    console.log(paramsEnvio)
    console.log(params)
    let server
    var options : FileUploadOptions;

    server = 'my URL'
    //server = this.urlSPE + 'salvarMalote'
    options = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,

    headers: {
        Connecection: "close"
    },
    params: {
        parametrosJson : params
    }
    }
    
    let id = Date.now()
    //Verificação de progresso 

    this.fileTransfer.onProgress((progressEvent) => {
      let perc
      if (progressEvent.lengthComputable) {
          perc = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
          this.setPorcentagem(perc, id, payload.discription,0,0)
      } else {
          perc++
      }
    });

    //upload

    console.log(filePath, server, options)

    return this.fileTransfer.upload(filePath, server, options).then((data) => {
        let returned = JSON.parse(data.response)
        if (retorno.sucesso) {
          let savedId = returned.return.id              //Terá valor apenas quando malote for salvo np servidor
          console.log('Id Malote Salov: ' + savedId)
          this.setPorcentagem(100, id, payload.discription,savedId,0)
        } else if (!retorno.sucesso) {
            console.log('erro')
            this.setPorcentagem(100, id, payload.discription,id,1)
            this.fileTransfer.abort()
        }
    }, (error) => {
        console.log(error)
        this.setPorcentagem(100, id, payload.discription,id, 1)
        this.fileTransfer.abort()
    });
  }

  //Metodos Observable

  setPorcentagem(perc, id, discription,savedId, status) {
    let dataEnv
    let percent;
    let aux;
    let already = this.percent.findIndex(i => {
        return i.value.id == id
    })
    dataEnv = this.datePipe.transform(Date.now(), 'dd/MM/yyyy HH:mm')
    if (perc == 1) {
        percent = perc / 100
        aux = perc
        this.ref.tick();
    } else if (perc == 100) {
        percent = 0
        aux = 0
        this.ref.tick();
    } else {
        percent = perc / 100
        aux = perc
        this.ref.tick();
    }
    console.log(status)
    if (already != -1) {
        let value = this.percent[already].value;
        value.percent = percent;
        value.aux = aux;
        value.date = date,
        value.savedId = savedId
        value.status = status
        this.percent[already].next(value)
        this.ref.tick();
    } else {
        this.percent.push(new BehaviorSubject({ id: id, aux: aux, percent: percent, name: discription, date: date, savedId:savedId, status:status}))
    }
  }


  getPercentObservable(): Array<BehaviorSubject<{ id: string, percent: string }>> {
    return this.percent;
  }

HTML:

<ion-item *ngFor="let item of apiService.getPercentObservable()" (click)="detalharItem(item)">
    <ion-grid *ngIf="item|async">
      <ion-row>
        <ion-col size="6">
          <ion-label class="discription" text-wrap>{{item.value.name}}</ion-label>
        </ion-col>
        <ion-col></ion-col>
        <ion-col size="5">
          <ion-text class="hour" *ngIf="item.value.percent != 0">Uploading...</ion-text>
          <ion-progress-bar  type="indeterminate" class="hour" color="secondary" *ngIf="item.value.percent != 0"> </ion-progress-bar>
          <!-- <ion-progress-bar class="horario" color="secondary" [value]="item.value.porcentagem" *ngIf="item.value.porcentagem != 0"></ion-progress-bar> -->
          <ion-label class="discription"  *ngIf="item.value.percent == 0 && item.value.status == 0" text-wrap>{{item.value.date}}</ion-label>
          <ion-label *ngIf="item.value.status == 1"><ion-icon [src]="personalizado"></ion-icon></ion-label>
        </ion-col>
      </ion-row>
    </ion-grid>
  </ion-item>

Hi

There is a lot going on here. Maybe from the start. The Behaviorsubject needs to contain the array of things you like to display or the progress percentage of the loader? I am not sure if it is smart to have it contain both.

if it needs to be the percentage, then you would do:

percent: BehaviorSubject<number> = new BehaviorSubject(0);

If it needs to be the array with the element structure you show (but without percentage):

arrayOfItems: BehaviorSubject<{ id: string, aux: number, name: string, date:string, savedId: string}[]> = new BehaviorSubject([]);

Next, you are creating a truckload of new BehaviorSubjects using the push statement in the bottom. Generally for observering one stream, one would need only one BehaviorSubject, which is instantiated in the upper part. (as a common pattern).

Why do u think u need an BehaviorSubject? To capture progress of the file loader which runs maybe outside of the change detection of Angular? Maybe use ngZone or something?

Maybe you want to look up some examples by Josh Morony on BehaviorSubject?

Hello, thanks for replying, I am using it this way because I need to monitor each submission in a particular way, showing a progress bar for each submission, only with BehaviorSubject I was unable to achieve this

Have you seen this?

This handles it without behaviorsubject.

1 Like

Thanks but for the project’s limitations I’m having to work with httpNative and fileTransfer. Besides, this way after sending it, it leaves the list?