Ionic 2 提供程序可观察的取消订阅



我正在开发一个 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 的用户数据。我正在使用 takeUntil 来处理此可观察量的取消订阅,一旦我离开页面并在提供程序上调用 dispose。我的问题是当我尝试重新导航到我已经取消订阅 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[]=[];

当您订阅可观察对象时,将其推送到阵列中

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

最新更新