I use the async pipe in my templates for all store select values as it does all the clean up, including unsubscribing, on its own.
But when i manually subscribe to a value in my auth gaurd, would i need to unsubscribe this? If yes, then what would be the best way to do that?
@Injectable()
export class AuthGaurd implements CanActivate{
constructor(
private store: Store<fromRoot.State>,
private router: Router
){}
canActivate(){
this.store.select(getLoggedInState).subscribe(res => {
if(res){
return true
}else {
this.router.navigate(['/login']);
}
});
return false;
}
}
You should use take
to get just the first value:
canActivate(){
this.store.select(getLoggedInState).take(1).subscribe(res => {
if(res){
return true
}else {
c this.router.navigate(['/login']);
}
});
return false;
}
}
take(n)
makes the observable take the first n
values it receives and then complete. You would not need to unsubscribe in this case.