捕获AngularFire2 V5错误



我正在转换使用firebase存储的使用来使用angularFire2库(当前v5.0.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);
    });

在其最基本的情况下,观察者会进行错误回调,以接收可观察到的流中的任何未手持错误。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以及可观察到的差异处理错误处理的文章:link1,link2

以下解决方案为我工作

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

最新更新