代码之家  ›  专栏  ›  技术社区  ›  Xerri

Angularfire2 v5中捕获错误

  •  0
  • Xerri  · 技术社区  · 6 年前

    我正在将Firebase存储的使用转换为使用Angularfire2库(目前为v5.0.0-rc.5-next),这意味着我现在使用的是可观察的而不是承诺。

    如何捕捉错误,例如 storage/object-not-found 并做出相应的反应?

    这是当前我的代码,但我无法添加 catch 我发现了一些例子。

    const avatarRef =  this.afStorage.ref('${userId}/avatar/${this.avatarThumbnail}${user.avatar}');
    
    avatarRef.getDownloadURL()
        .take(1)
        .subscribe((avatarUrl) => {
            resolve(avatarUrl);
        });
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Oleksii Miroshnyk    6 年前

    最基本的情况是,观察者通过错误回调来接收可观察流中任何未处理的错误。 getDownloadURL() 返回可观察的,这就是您需要订阅的原因。如果您收到错误(未找到文件或其他),您将仅从错误回调调用代码。

    avatarRef.getDownloadURL()
    .take(1)
    .subscribe((avatarUrl) => {
        // Do something with avatarUrl here
       console.log(avatarUrl);
    }, (error) => {
       // Handle error here
       // Show popup with errors or just console.error
       console.error(error);
    });
    

    此外,我建议您阅读有关使用RxJS进行错误处理以及Observable和Promise之间的区别的文章: link1 ,则, link2

        2
  •  0
  •   amit ghosh    4 年前

    以下解决方案对我有效

    startUpload(file) {
    
        // The storage path
        const path = `image${new Date().getTime()}.jpg`;
    
        // Reference to storage bucket
        const ref = this.storage.ref(path);
        let image = 'data:image/jpeg;base64,' + file;
        // The main task
        return new Promise((resolve, reject) => {
          const upload = ref.putString(image, 'data_url');
          const sub = upload.snapshotChanges().pipe(
            finalize(async () => {
              try {
                const photoURL = await ref.getDownloadURL().toPromise();
                this.message.senderUid = this.currentUser.uid;
                this.message.receiverUid = this.selectedUser.uid;
                this.message.text = this.inputText && this.inputText !== '' ? this.inputText : 'File';
                this.message.senderName = this.currentUser.name;
                this.message.chatId = this.chatId;
                this.message.file = photoURL;
                this.firebaseService.insertMessage(this.message)
                  .then(() => {
                    this.inputText = '';
                    this.message.file = null;
                    this.scrollToBottomOnInit();
                  });
    
                resolve({photoURL})
              } catch (err) {
                this.inputText = '';
                this.message.file = null;
                reject(err)
              }
              sub.unsubscribe()
            })
          ).subscribe((data) => {
            console.log('storage: ', data)
          })
        })
      }

    资料来源: https://github.com/angular/angularfire/issues/1736#issuecomment-515798352