Reputation: 61
//Parent component
subscription: Subscription[] = [];
//stuff
constructor(private http: HttpService, private route: ActivatedRoute) {
const subLoading = this.http.loading.subscribe((loading: boolean) => {
this.loading = loading;
});
//stuff to do
this.subscription.push(subLoading);
this.subscription.push(subData);
}
ngOnDestroy() {
console.log("logged if logging out directly from here")
this.subscription.forEach((sub) => {
sub.unsubscribe();
});
}
//Child component
Linked with a route from child to parent (Parent URL : domain/list , eg.: Child URL: domain/list/item/53 )
//App-routing
const routes: Routes = [
{ path: '', component: AuthComponent },
{ path: 'list/:pageID', component: ListComponent, canActivate: [AuthGuard] },
{
path: 'list/item/:id',
component: ListItemDetailComponent,
canActivate: [AuthGuard],
},
];
//Header
export class HeaderComponent implements OnInit {
public isLoggedIn = false;
private userSub: Subscription;
constructor(private authService: AuthService) {}
ngOnInit(): void {
this.userSub = this.authService.user.subscribe((user) => {
this.isLoggedIn = !!user ? true : false;
});
}
ngOnDestroy(): void {
this.userSub.unsubscribe();
}
logOut() {
this.authService.logOut();
}
}
In the header I unsubscribe,destroy the user(BehaviourSubject) and logOut
BUT many BehaviourSubjects that I subscribed to in the Parent component doesnt get destroyed if I logOut while staying at the Child Component
Any solution?
Upvotes: 0
Views: 799
Reputation: 438
just a point, you dont destroy BehaviourSubjects , you destroy subscriptions, thats why other componentes that have some subscription to the same behaviorSubject keep with their subscripcions. I thing you can use other subject to emit when Logout, and use it in each subscripcion, with takeUntil() operator. (takeUntil rxjs operator examples)
Update:
AuthService:
logoutSubject = new Subject(); //
logout$ = this.logoutSubject.asObservable();
inside any component you want to take subscription of user until logout
this.authService.user
.pipe(takeUntil(this.authService.logout$)) // it will managing subscription until logout observable emit
.subscribe((user) => {
this.isLoggedIn = !!user ? true : false;
});
I think this should resolve your problem, but take in mind if you try to login again , that subscription do not work because has been terminated.
Upvotes: 1