ionic2 - Ionic 2 Provider 可观察取消订阅

标签 ionic2 observable

我正在开发一个 Ionic 应用程序,并且遇到了关于何时取消订阅提供程序中使用的可观察对象的问题。目前我正在做的是在进入页面之前检查使用是否经过身份验证的页面。然后,如果他们通过身份验证,我会从 firebase 返回用户数据。这是页面上使用的函数

ionViewCanEnter() {

return new Promise((resolve, reject) => {
  this.auth.isBusiness()
    .then(user => {
      this.currentUser = user;
      resolve(true);
    })
    .catch(error => {
      console.log(error);
      this.presentToast()
      reject(false)
    });
});
}

我调用的函数存在于提供程序中。我从 firebase 订阅我的用户数据。一旦我离开页面并在提供者上调用 dispose,我将使用 takeUntil 来处理此可观察对象的取消订阅。我的问题是,当我尝试重新导航到页面时,我已经取消订阅 destroy$ 变量。我是否应该取消订阅提供者内部的可观察量,因为页面之间使用了相同的提供者并且没有重新初始化,或者我还需要做其他事情。每当加载页面时,是否需要手动调用提供程序的 init 函数?

private destroy$: Subject<any>
 public isBusiness() {
    return new Promise((resolve, reject) => {
      this.isAuthenticated()
        .then(user => {
          this.userProvider.getUser(user["uid"]).takeUntil(this.destroy$).subscribe(searchedUser => {
            if (searchedUser.userType === "business") {
              resolve(searchedUser);
            } else {
              reject("You are not a business");
            }
          })
        }).catch(err => {
          reject(err);
        });
    });
  }
  public dispose() {
    this.destroy$.next(true);
    this.destroy$.unsubscribe();
  }

感谢您的帮助!

最佳答案

您可以使用订阅来实现此目的,如下所示,

import { Subscription } from "rxjs/Subscription";

服务中创建一个变量

private subscriptions: Subscription[]=[];

当你订阅一个 Observable 时,将其推送到你的数组中

public isBusiness() {
    return new Promise((resolve, reject) => {
      this.isAuthenticated()
        .then(user => {
        this.subscriptions
            .push(
                this.userProvider
                    .getUser(user["uid"])
                    .takeUntil(this.destroy$)
                    .subscribe(searchedUser => {
                        if (searchedUser.userType === "business") resolve(searchedUser);
                        else reject("You are not a business");
                    }))
        }).catch(err => {
          reject(err);
        });
    });
}

当页面被破坏时,您可以

public dispose() {
    this.subscriptions.forEach(item=>{
    item.unsusbscribe();
    });

}

销毁该组件时调用 dispose 方法。

关于ionic2 - Ionic 2 Provider 可观察取消订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45258784/

相关文章:

javascript - View 中的 Ionic2 ngFor 未更新

javascript - 根据下拉列表中选择的项目过滤 JSON API 数据

dart - 在Dart中将可观察属性从一个对象转发到另一个

Angular 与 angular/cli - 无法找到 rxjs 运算符 mergeDelayError

angular - 在 *ngFor-- IONIC2/Angular2 中迭代两个数组

angular - 无法从 Ionic 中的 ion-select 获得选定的值

javascript - 使用动态函数设置给定类的背景颜色

javascript - 从另一个 observable 内部的 observable 返回对象

javascript - RxJs Observable Zip 可观察对象数组

ios - 从单个 Observable 创建多个 Observable - RxSwift