0

For some reason my listImage() method returns a null I don't know what I could be doing wrong. for some reason my listImage() method returns null.

import {
  Injectable,
}
from '@angular/core'
declare
var firebase;

@
Injectable()
export class StorageService {

  img:any;

  listImage() {

    var getImages = firebase.database().ref('flats').once('value');
    getImages.then(snapshot => {
      var imgName = snapshot.val();
      var names;

      snapshot.forEach(imgName => {
        names = imgName.val();
        let i = names.image;
        //console.log(i);
        let key = imgName.key
        firebase.storage().ref(i + '.jpg').getDownloadURL().then(url => {
          this.img = url;
        });
      })
    })
    return this.img;
  }

}

could it be the forEach() restricting it

constructor(public navCtrl: NavController, service: StorageService) {
  this.service = service;
  var img = this.service.listImage();
  console.log(img); //this returns null what could be the issue?
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Muzi Jack
  • 788
  • 1
  • 7
  • 20

1 Answers1

1

The problem is that JS is asynchronous. It has nothing to do with Angular 2 itself.

When you call the listenImage() function you are using a promise which is the correct way to handle this. But look at your return command: return this.img;

It is not handled inside the promise, since it is not inside any .then() So you basically call your getImages() promise and jump to the return command without waiting for any results.

In addition to that, you are making asynchronous calls inside the foreach which is not asynchronous.

Here is a good answer that describes how you should correctly work with promises during asynchronous tasks. And you should also definitely have a look at this to see how you should deal with the foreach and other loops when working with promises (it's under Rookie Mistakes #2).

Community
  • 1
  • 1
EDREP
  • 78
  • 1
  • 8