Luiz Ricardo Cardoso
Luiz Ricardo Cardoso

Reputation: 1624

Using async await firebase storage

I need to wait for the file to be uploaded before taking any action.

I developed the following code but I can not get downloadURL;

I want to get downloadURL using async method to have a good code.

I checked and there is no error while uploading the image, since the image is uploading normally but I can not get downloadURL after upload.

auth.service.ts

async changeUserAvatar(avatar: any): Promise<firebase.storage.UploadTaskSnapshot> {
    try {
        let storageRef = firebase.storage().ref();
        return await storageRef.child(`avatars/${this.userLogged.uid}`).put(avatar);
    } catch (error) {
        alert(error);
    }
}

my-component.ts

saveUser(): void {
    this.chekcUserAdmin()
        .pipe(takeUntil(this._unsubscribeAll))
        .subscribe(async (user: any) => {
            if (!user.admin) {

                const upload = await this._authService.changeUserAvatar(this.avatarUpload);

                // #FIX-ME
                // The upload.downloadURL here is coming undefined;
                user.avatar = upload.downloadURL; 
                await this.updateUser(user);

                alert('User saved!');
            }
        });
}

Upvotes: 1

Views: 4005

Answers (2)

Bacar Pereira
Bacar Pereira

Reputation: 1145

1. Created a service to upload file

export class FileUploadService {

 constructor(private afStorage:AngularFireStorage) { }

 async uploadFile(filePath:string,fileToUpload) {
    return (await this.afStorage.upload(filePath, fileToUpload)).ref;
  }
}

2. Inject a service in your component and call uploadFile(param1,param2) after select the photo

export class Component implements OnInit {
       ...

       constructor(private fileUploadService:FileUploadService) {}

       async uploadFile(filePath:string,fileToUpload){
          try{
              let ref = (await this.fileUploadService.uploadFile(filePath, fileToUpload))
              let urlDownloadImage = await ref.getDownloadURL();
              console.log(urlDownloadImage)
          }catch(exception){
              console.log("exception "+exception)
         }
       }
  }

Upvotes: 0

Samuel Vaillant
Samuel Vaillant

Reputation: 3847

You have to use await upload.ref.getDownloadURL() to be able to retrieve the URL. You can find some examples in the Firebase documentation.

Upvotes: 1

Related Questions