How can I get image from Firebase Storage and display them in Angular 2 ngFor

taku845 picture taku845 · Dec 9, 2016 · Viewed 10.2k times · Source

I'm trying to display image in *ngFor which I downloaded from Firebase Storage.

I succeeded fetching image data from storage, but I don't know how to set image data in ngFor statement.

Let me show you my code here.

<ons-list-item class="list__item list__item--chevron" tappable *ngFor="let request of requests | async" (click)="pushToDetail(request)">
    <ons-row>
      <ons-col width="20%"><img [src]="userProfileImg"></ons-col>
      <ons-col style="padding-left:20px;">
        <p class="name"><i class="fa fa-venus fa-fw" aria hidden="true"></i>{{request.nickName}}</p>
      </ons-col>
    </ons-row>
</ons-list-item>

And this is the code to download image. I wrote this one in foreach when I subscribed FirebaseListObservable data.

getProfileImageUrl(userId: string) {
    const userStorageRef = firebase.storage().ref().child('images/users/' + userId + "_users.jpg");
    userStorageRef.getDownloadURL().then(url => {
      this.userProfileImg = url
    });
  }

Then I'd like you to teach me how to literate images from Firebase Storage. Any suggestions?

Answer

Mohamed picture Mohamed · Apr 11, 2017

Save name of the picture, and short path to your database.

Use following code to upload base64 image;

uploadImage(name, data) {
    let promise = new Promise((res,rej) => {
        let fileName = name + ".jpg";
        let uploadTask = firebase.storage().ref(`/posts/${fileName}`).put(data);
        uploadTask.on('state_changed', function(snapshot) {
        }, function(error) {
            rej(error);
        }, function() {
        var downloadURL = uploadTask.snapshot.downloadURL;
            res(downloadURL);
        });
    });
    return promise;
 }

it's just 2 lines of code to get actual url securely with permissions.

this.storageRef = firebase.storage().ref().child('images/image.png');
this.storageRef.getDownloadURL().then(url => console.log(url) );

If you need more optons like passing strings, URI's etc, you can checkout my blog post about uploading, and getting data from firebase storage using angularfire2.

I hope it helps somebody.