【问题标题】:Using async await firebase storage使用 async await firebase 存储
【发布时间】:2019-06-08 21:31:36
【问题描述】:

我需要等待文件上传后才能采取任何行动。

我开发了以下代码,但我无法获取downloadURL

我想用 async 方法得到downloadURL 有一个好的代码。

我检查了上传图片时没有错误,因为图片上传正常,但上传后我无法获取downloadURL

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!');
            }
        });
}

【问题讨论】:

    标签: angular typescript firebase firebase-storage


    【解决方案1】:

    您必须使用 await upload.ref.getDownloadURL() 才能检索 URL。你可以找到一些例子in the Firebase documentation

    【讨论】:

      【解决方案2】:

      1.创建了一个上传文件的服务

      export class FileUploadService {
      
       constructor(private afStorage:AngularFireStorage) { }
      
       async uploadFile(filePath:string,fileToUpload) {
          return (await this.afStorage.upload(filePath, fileToUpload)).ref;
        }
      }
      

      2。在你的组件中注入一个服务并在选择照片后调用uploadFile(param1,param2)

      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)
               }
             }
        }
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2017-09-28
        • 2021-01-13
        • 2021-09-25
        • 2019-07-27
        相关资源
        最近更新 更多