Javascript 使用什么来代替subscribe()作为可观察对象
我想在Firebase authState更改时关闭登录对话框。我在网上读到,如果未调用Javascript 使用什么来代替subscribe()作为可观察对象,javascript,angular,firebase,google-cloud-firestore,rxjs,Javascript,Angular,Firebase,Google Cloud Firestore,Rxjs,我想在Firebase authState更改时关闭登录对话框。我在网上读到,如果未调用unsubscribe()函数,则subscribe()函数将导致数据泄漏,因此,我希望替换该函数。这是我的密码: this.user = this.auth.authState.pipe( switchMap( (user) => { if(user) { return (this.firestore.collection('users').doc(user.uid).valu
unsubscribe()
函数,则subscribe()
函数将导致数据泄漏,因此,我希望替换该函数。这是我的密码:
this.user = this.auth.authState.pipe(
switchMap( (user) => {
if(user) {
return (this.firestore.collection('users').doc(user.uid).valueChanges() as Observable<User>)
} else {
return of(null);
}
})
);
这是我尝试过的,但我认为我没有正确使用map函数:
this.authService.user.pipe(
map( (user) => {
if(user) {
this.isLoading = false;
this.dialogRef.close();
}
})
)
提前谢谢 订阅功能本身并不坏,也没有内存泄漏。当组件代码或服务代码被销毁时,如果您没有取消订阅
订阅
或完成可观察
,则会出现问题
但这完全取决于你想做什么:
如果这是根服务中的全局侦听器。你不必在意它,因为服务的生命周期与你的整个应用程序是一样的
如果它是组件中的侦听器,则需要确保在组件被销毁时取消订阅:
@Component({...})
export class SomeComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor(private authService: AuthService) {}
checkLogin(): void {
this.authService.user.pipe(
filter((user) => !!user),
takeUntil(this.destroy$)
).subscribe((user) => {
this.isLoading = false;
this.dialogRef.close();
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
在以下情况下,将取消订阅:
- 使用
takeUntil(…)
- 使用
和过滤器(…)
获取(1)
只有在第二种情况下,它才能到达subscribed方法。可观察的.toPromise()是否符合要求?您可以使用诸如
take(1)
或takeUntil()
之类的运算符来确保链始终完成toPromise()
只有在可观察对象完成时才会泄漏,因此我认为没有理由避免使用subscribe()
。非常感谢takeUntil()
是我所缺少的。我需要编辑你的代码,让它按我所希望的那样工作。以下是我使用的:this.authService.user.pipe(map(user=>!!user),takeUntil(this.dialogRef.beforeClosed()).subscribe((isLoggedIn)=>{if(isLoggedIn){this.isLoading=false;this.dialogRef.close();})代码>
@Component({...})
export class SomeComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor(private authService: AuthService) {}
checkLogin(): void {
this.authService.user.pipe(
filter((user) => !!user),
takeUntil(this.destroy$)
).subscribe((user) => {
this.isLoading = false;
this.dialogRef.close();
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@Component({...})
export class SomeComponent {
constructor(private authService: AuthService) {}
checkLogin(): void {
this.authService.user.pipe(
filter((user) => !!user),
take(1),
takeUntil(this.dialogRef.beforeClosed)
).subscribe((user) => {
this.isLoading = false;
this.dialogRef.close();
});
}
}