【问题标题】:Ionic 2 Provider Observable UnsubscribingIonic 2 Provider Observable 退订
【发布时间】:2017-07-23 04:36:34
【问题描述】:

我正在开发一个 Ionic 应用程序,但我遇到了关于何时取消订阅提供程序中使用的 observable 的问题。目前我正在做的是在一个页面上,我在进入页面之前检查使用是否经过身份验证。然后,如果他们通过身份验证,我会从 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 来处理此 observable 的取消订阅。我的问题是当我尝试重新导航到我已经取消订阅 destroy$ 变量的页面时。我是否应该从提供程序中取消订阅 observables,因为在页面之间使用相同的提供程序并且没有重新初始化,或者我需要做其他事情。每当我加载我的页面时,我是否需要为提供程序手动调用一个 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();
  }

感谢大家的帮助!

【问题讨论】:

    标签: ionic2 observable


    【解决方案1】:

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

    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 方法。

    【讨论】:

    • 问题是可观察的在我的提供者中,而您建议将订阅数组放入组件中。提供者将无权访问此订阅列表。您是否建议每次进入页面时将此列表传递给提供者?
    • @user4717937 在服务中创建变量
    • 要不要在 dispose 完成后清空订阅数组?
    • 是的。当组件ngOnDestroy调用this.service.dispose()
    • 不,我的意思是我应该在 dispose 函数的末尾做this.subscriptions = []; 吗?
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2016-10-25
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 2017-10-06
    • 2017-06-27
    相关资源
    最近更新 更多