捕获 Angularfire2 v5 错误

Catch in Angularfire2 v5 error

我正在将 Firebase 存储的使用转换为使用 Angularfire2 库(当前为 v5.0.0-rc.5-next),这意味着我现在使用的是 observables 而不是 promises。

如何捕获 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() returns Observable 这就是您需要订阅的原因。如果您遇到错误(找不到文件或其他错误),您将仅从错误回调中调用代码。

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

以下解决方案对我有用

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