【问题标题】:Offline Promise Handling in Angularfire2Angularfire2 中的离线 Promise 处理
【发布时间】:2019-05-29 07:05:48
【问题描述】:

据我了解,Angularfire2 在查询成功运行时返回一个 Promise (返回数据时的 fetch 除外)。

功能

我有一个应用程序,在其中保存项目时会调用一个函数,如果设置查询成功运行(即它接收到 Promise),它会导航到上一页。 当应用程序在线但应用程序也需要离线工作时,它可以完美运行。我已启用持久性并为其配置了服务人员

问题

但是离线时,查询返回Promise后的代码没有被调用。那么离线期间应该是什么预期的逻辑或行为。

                this._itemService.setItem(item).then(()=>{
                    const message = item.name + saveMessage;
                    this.snackBar.open(message," ",{duration:2000});
                    this.location.back();

                }

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    promise 之后的代码未被调用会导致您收到错误,因为您在离线时无法访问源代码。 在 Promise 之后添加一个 ErrorHandling,如下所述: Using success/error/finally/catch with Promises in AngularJS

    在 ErrorHandling 中,您可以添加应用离线时的行为。

    this._itemService.setItem(item).then(()=>{
        const message = item.name + saveMessage;
        this.snackBar.open(message," ",{duration:2000});
        this.location.back();
    ).catch((e) => {
        //Do what you want when you don't get the Promise
        this.location.back();
    });
    

    【讨论】:

    • 感谢您的快速回复。抱歉,在实施上述解决方案后,我遇到了另一个问题。 Angularfire2 在离线时不会返回错误,因此永远不会调用 catch 块。
    • 你使用 rxjs 库中的承诺吗?并且可以向我们展示您的 itemService 中的代码,特别是函数 setItem。谢谢
    • promise 来自 javascript 库而不是 rxjs
    【解决方案2】:
               let itemPromise= this._itemService.setItem(item);
    
                if(navigator.onLine && itemPromise instanceof Promise){
                    itemPromise.then(()=>{
                        const message = item.name + "account saved";
                        this.snackBar.open(message," ",{duration:2000});
    
                       ...More code
                        this.closeClicked();
                    });
                }else{
    
                    const message = item.name + "account saved";
                    this.snackBar.open(message," ",{duration:2000});
                    this.closeClicked();
                }
    

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 2010-12-23
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2015-03-23
      • 1970-01-01
      相关资源
      最近更新 更多