简体   繁体   中英

Firebase Storage | Angular 2 - Proper way to display image after upload

When creating an event, I also upload an image to Firebase Storage.

Then I create an array this.eventz to display the events on the home page. For each event I want to retrieve the image as well, but I get a Firebse error:

FirebaseStorageError {code_: "storage/object-not-found", message_: "Firebase Storage: Object 'events/-KxCuUuss1I2uFolk99m/-KxCuUuss1I2uFolk99m_main.png' does not exist.", serverResponse_: "{↵ "error": {↵ "code": 404,↵ "message": "Not Found. Could not get object"↵ }↵}", name_: "FirebaseError"}

I understand that the image isn't uploaded yet when I want to include it in the array but I don't know how to fix my problem. The code works fine. It displays all the events, adds images to each one ... it's just that error when creating a new event.

getEventImage(event) {

if (event) {
            const mainPhotoRef = firebase.storage().ref('events');
            console.log(mainPhotoRef);
            mainPhotoRef.child(`/${event.key}/${event.key}_main.png`).getDownloadURL()
                .then(url => this.makeEvents(url, event))
        }
    }

makeEvents(url, event) {
    console.log(url);
    if (url) {
        try {
            event.img = url;
            let index = _.findIndex(this.eventz, ['key', event.key]);

            if (index >= 0) {
                this.eventz.splice(index, 1);
            }

            this.eventz.push(event);
        } catch (err) {
            console.log(err);
        }
    }
}

I fixed my problem by saving the url to the event object when creating it. I would like to know if I am uploading correctly.

private uploadPhoto(itemKey): void {
    this.myPhotosRef.child(itemKey).child(`${itemKey}_main.png`)
      .putString(this.myPhoto, 'base64', { contentType: 'image/png' })
      .then((savedPicture) => this.updateEventImage(savedPicture.downloadURL, itemKey));
  }

  updateEventImage(url, itemKey) {
    console.log(url);
    const newEvent = this.db.object(`events/${itemKey}`)
    newEvent.update({ eventImage: url });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM