我已经阅读了文章和视频,并且了解如何取消订阅,但我仍然无法理解何时我需要取消订阅。这是我的项目中的一些简化代码。我正在订阅我拥有的服务中的可观察对象,并且我还订阅了我为项目创建的 Firebase Firestore 中的数据。
matches.component.ts
constructor(public afs: AngularFirestore, public authService: AuthService) {
}
subscription: Subscription | undefined
authSubscription: Subscription | undefined
ngOnInit(): void {
this.authSubscription = this.authService.adminInfo.subscribe(info => {
console.log(info)
})
this.subscription = this.afs.collectionGroup('matches', ref => ref.orderBy('date')).snapshotChanges().subscribe(async (resp) => {
for (const item of resp) {
console.log(item)
}
});
}
auth.service.ts
constructor(public afs: AngularFirestore, public authService: AuthService) {
}
participantSub: Subscription | undefined
private adminInfoSub = new BehaviorSubject({uid: ""})
adminInfo = this.adminInfoSub.asObservable();
makeData() { //Gets called when the user logs in
this.participantSub = this.afs.collectionGroup('participants').snapshotChanges().subscribe(info => {
const adminInfo = {
displayName: info.displayName,
uid: info.uid,
tournaments: info.tournaments
}
this.adminInfoSub.next(adminInfo)
})
}
匹配组件是一个选项卡,您可以在应用程序中导航到和离开,而身份验证服务只是常规的 Angular 服务。所以我的问题是,我是否需要取消订阅这些订阅,为什么或为什么不?
您需要取消订阅任何未完成的可观察对象。
除非在主题上调用
complete()
或抛出错误,否则它不会完成。
因此,就您而言,如果您不取消订阅,您将会遇到内存泄漏!