Help with product registration with images

Asked

Viewed 52 times

2

I am trying to register products, where it is possible to register more than one photo per product. But in the service that I created, I call a for to fill the image matrix, this happens very well. But I have a difficulty in logic, to call the save function, because it is inside the for, it is called according to the number of images that the user selects, if the user selects 2 images, he registers two products, if he selects 3 images, register 3 images and so on. I’d like some help to fix this little problem.

//esse é o meu service

        public uploadAndSave(item: any) {
        let produto = { $key: item.key,
                    nome: item.nome, 
                    url: [], 
                    fullPath: [],
                    preco: item.preco,
                    qtd: item.qtd, 
                    marca: item.marca,
                    tipo: item.tipo,
                    tamanho: item.tamanho,
                    cor: item.cor,
                    codigoBarras: item.codigoBarras
                  };

    if (produto.$key) {
      this.save(produto);
    } else {
      for (let i = 0; i < item.fileToUpload.length; i++){
        let storageRef = this.fb.storage().ref();
        let basePath = '/produtos/';
        produto.fullPath[i] = basePath + '/' + produto.nome + '.png';
        let uploadTask = storageRef.child(produto.fullPath[i]).putString(item.fileToUpload[i], 'base64');

        uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
        (snapshot) => {
          var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          console.log(progress);
        },
        (error) => {
          console.error(error);
        },
        () => {
          produto.url[i] = uploadTask.snapshot.downloadURL;
          this.save(produto);
        }); 
      }
    }
  }

//e aqui a minha chamada no meu arquivo ts : 

      //Cadastra o produto com foto
      cadastrarProduto() {
      this.produtosProvider.uploadAndSave({
          key: this.produtoKey,
          nome: this.produtoNome,
          tipo: this.produtoTipo,
          qtd: this.produtoQtd,
          tamanho: this.produtoTamanho,
          marca: this.produtoMarca,
          cor: this.produtoCor,
          preco: this.produtoPreco.replace(',','.'),
          fileToUpload: this.fileToUpload,
          codigoBarras: this.produtoCodigoBarras
       });
       this.toastCadastro();
       this.fechar();
      }
  • Guys, any help with that? I still can’t figure it out

1 answer

0

I’m not sure I understand your problem, but it seems you’re making a for, which is a synchronous method and inside it firing various asynchronous methods, which means that the for will finish and follow before the uploads finish, if what you want is to bring this upload code to a "synchronous" mode pro for waiting, you can convert the observable into promisse and use the async await, you will "lose" the status of progress in that case, but I believe the for will wait to upload in this case.

look at an example of "asynchronous" upload in firebase Storage

async upload(file) {
    const fileName = `${new Date().getTime()}-${file.name}`;
    const filePath = `${this.PATH}/${fileName}`;
    const fileRef = this.afStorage.ref(filePath);
    await this.afStorage.upload(filePath, file).snapshotChanges().toPromise();
    const urlFile = await fileRef.getDownloadURL().toPromise();
    return { urlFile: urlFile, fileName: file.name };
  }

within the for would look like this:

for (let i = 0; i < item.fileToUpload.length; i++){
await upload(item.fileToUpload[i])
}

Browser other questions tagged

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