Create array with Firebase return data

Asked

Viewed 157 times

0

You would need to create a new array from the return of the Firebase image URL

The newImgList array receives nothing.

task ts.

 imgList: [];
 newImgList: any = [];

 constructor(...) {

    this.tarefaId = this.navParams.get('tarefaId');
    this.imgList = this.navParams.get('imgList');
    this.listImage(this.tarefaId);    
    this.getTarefa();
  }



  listImage (tarefaId: string) {
    for (let i = 0; i < this.imgList.length; i++) {
      let storageRef = firebase.storage().ref();
      let imageRef = storageRef.child(`tarefas/${tarefaId}/${this.imgList[i]}`);
      imageRef.getDownloadURL().then(function (url) {    
        this.newImgList.push(url);
      }).catch(function (error) {
        alert("erro");
      });
    }
  }
  • What error are you getting?

  • is not populating the "newImgList" array. if I give an empty console.log to it.

  • it will only be populated within the then pq is asynchronous

  • @Eduardovargas, I’m kind of raw at it. I could exemplify?

1 answer

0


You will only be able to see the content on the console when the list is finished receiving the asynchronous data from the server. Use ASYNC/AWAIT. Give a study on ASYNC/AWAIT, it is very important for those who work with server requests.

ps: I did not test the code.

 imgList: [];
 newImgList: any = [];

 constructor(...) {

    this.tarefaId = this.navParams.get('tarefaId');
    this.imgList = this.navParams.get('imgList');
    this.listImage(this.tarefaId);    
    this.getTarefa();
  }



  async listImage (tarefaId: string) {
    let storageRef = firebase.storage().ref();
    for (let i = 0; i < this.imgList.length; i++) {
      let imageRef = storageRef.child(`tarefas/${tarefaId}/${this.imgList[i]}`);
      await imageRef.getDownloadURL().then(function (url) {    
        this.newImgList.push(url);
      }).catch(function (error) {
        alert("erro");
      });
    }

    console.log(this.newImgList);
  }
  • Ahh. "Let storageRef = firebase.Storage(). ref();", use outside the loop, vc do not need to catch the same reference several times.

Browser other questions tagged

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