Individual progress bar for each shipment

Asked

Viewed 63 times

1

Today I can perform file uploading by displaying a progress bar. when I make a new request, the values in the progress bar alternate between the values of each upload. This way, I would like to show the progress bar individually for each document that is being sent, being able to add in the layout the description and the progress bar of the respective upload.


HTML:

<ion-item *ngIf="aux != 0">
    <ion-text >{{aux}}% </ion-text>
    <ion-label class="porcentagem"><ion-progress-bar [value]="porcentagem"></ion-progress-bar></ion-label>
    <ion-button color="danger" (click)="cancelarEnvio()">Cancelar</ion-button>
  </ion-item>

Page:

 ngOnInit() {
    this.apiService.getPorcentagemObservable().subscribe(res => {
      console.log('Novo Valor: ', res)
      
      if(res == 1){
        this.porcentagem = res / 100
        this.aux = res
      } else if (res == 100) {
        this.porcentagem = 0
        this.aux = 0
        this.changeDetectorRef.detectChanges()
      } else {
        this.porcentagem = res / 100
        this.aux = res
        this.changeDetectorRef.detectChanges() 
      }
    })
  }

Service:

import { Camera, CameraOptions, MediaType } from '@ionic-native/camera/ngx';
import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer/ngx';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  fileTransfer: FileTransferObject = this.transfer.create();
  private porcentagem = new BehaviorSubject(0)
  usuario:any   
  codigo:any


//=============================================> Construtor <=========================================

  constructor
  ( 
    private http: HTTP,
    private transfer : FileTransfer,

  ) {}

  salvarMalote(payload){
    console.log(payload)
    
    var filePath = payload.imageURI;
    var filename = filePath.split("/").pop();
    var extencao = filename.split(".").pop();
    let server
    var options : FileUploadOptions;

    let url //My url
    server = url 
    options = {
        fileKey: "file",
        fileName: filename,
        chunkedMode: false,

        headers: {
            Connecection: "close"
        },
        params: {
            Codigo: this.codigo,
            descricao: payload.descricao,
            email: this.usuario
        }
    }

 
    //Verificação de progresso 

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

    //upload

    console.log(filePath, server, options)
    return this.fileTransfer.upload(filePath, server, options).then((data) =>{
      let retorno = JSON.parse(data.response)
      console.log(retorno)
      if (retorno.sucesso) {
        this.setPorcentagem(100)
      } else {
        console.log('erro')
      }
      console.log()
    }, (error) => {
      console.log(error)
    });
  }

  //Metodos Observable

  setPorcentagem(perc){
    if (perc == 100) {
      this.porcentagem.next(0)
    } else{
      this.porcentagem.next(perc)
    }
  }

  getconst(): number {
    return  this.porcentagem.getValue()
  }
  
  getPorcentagemObservable():Observable<number>{
    return this.porcentagem.asObservable()
  }

  abortar(){
    this.porcentagem.next(0)
    this.fileTransfer.abort()
  }

}

Expected Result:

inserir a descrição da imagem aqui

2 answers

1


Good morning, you could test this solution, it may be that you need to adapt something, I have not tested completely.

HTML

 <ion-item *ngFor="let item of apiService.getPorcentagemObservable()" >
    <div *ngIf="item|async">
      <ion-text >{{item.value.nome}} {{item.value.porcentagem}}% </ion-text>
      <ion-label class="porcentagem"><ion-progress-bar [value]="{{item.value.porcentagem}}"></ion-progress-bar></ion-label>
    <ion-button color="danger" (click)="cancelarEnvio()">Cancelar</ion-button>
    </div>
  </ion-item>

Page

constructor(public apiService: ApiService) {}

Service

import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';
import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer/ngx';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class ApiService {

    fileTransfer: FileTransferObject = this.transfer.create();
    //   private porcentagem = new BehaviorSubject(0)
    private porcentagem: Array<BehaviorSubject<{ id: string, aux: number, porcentagem: string, nome: string }>> = []

    usuario: any
    codigo: any


    //=============================================> Construtor <=========================================

    constructor
        (
            private http: HTTP,
            private transfer: FileTransfer,

    ) { }

    salvarMalote(payload) {
        console.log(payload)

        var filePath = payload.imageURI;
        var filename = filePath.split("/").pop();
        var extencao = filename.split(".").pop();
        let server
        var options: FileUploadOptions;

        let url //My url
        server = url
        options = {
            fileKey: "file",
            fileName: filename,
            chunkedMode: false,

            headers: {
                Connecection: "close"
            },
            params: {
                Codigo: this.codigo,
                descricao: payload.descricao,
                email: this.usuario
            }
        }

        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, filename)
            } else {
                perc++
            }
        });

        //upload

        console.log(filePath, server, options)

        return this.fileTransfer.upload(filePath, server, options).then((data) => {
            let retorno = JSON.parse(data.response)
            console.log(retorno)
            if (retorno.sucesso) {
                this.setPorcentagem(100, id, filename)
            } else {
                console.log('erro')
            }
            console.log()
        }, (error) => {
            console.log(error)
        });
    }

    //Metodos Observable

    setPorcentagem(perc, id, filename) {
        let porcentagem;
        let aux;
        let already = this.porcentagem.findIndex(i => {

            return i.value.id == id
        })
        console.log(already);

        if (perc == 1) {
            porcentagem = perc / 100
            aux = perc
        } else if (perc == 100) {
            porcentagem = 0
            aux = 0
        } else {
            porcentagem = perc / 100
            aux = perc
        }

        if (already != -1) {
            let value = this.porcentagem[already].value;
            value.porcentagem = porcentagem;
            value.aux = aux;
            this.porcentagem[already].next(value)
        } else {
            this.porcentagem.push(new BehaviorSubject({ id: id, aux: aux, porcentagem: porcentagem, nome: filename }))
        }
    }


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


}
  • Thank you very much, tomorrow I will try this solution and I speak to you

  • The functionality is now perfect, before the progress bar was only loading at the end of the process, I tried to add the public changeDetectorRef : Changedetectorref, below each if in the setPontage() but he did not recognize it because it is a service, however I added the applicationRef.tick() which has a function and then it loaded normally

  • Great that it worked

  • Alison good afternoon, you would happen to know how to remove an item from the Array<Behaviorsubject and update the page upon completion of upload??

0

Hérick Raposo,

To remove an item from the array you can try this:

  removeBehaviorById(id) {
    this.porcentagem = this.porcentagem.map((behavior) => {
      if (behavior.value.id == id) {

        //Primeiro atualiza o status para null, pois os ouvintes vao entender que nao ha mais nada para atualizar
        behavior.next(null)
        // dar um unsubscribe para parar de emitir eventos
        behavior.unsubscribe()
      }

      // e por fim remove ele do array
      if (behavior.value.id != id) {
        return behavior;
      }
    })
  }
  • Thank you, I’ll try

  • Do you know if it is possible to refresh/refresh the page after this?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.