In my application, I have two main pages named Dashboard
and Transactions
, along with a component called Sidebar
responsible for navigation control.
The initial transition from the Dashboard
to the Transactions
page involves subscribing to the user state in the store. This process functions correctly, allowing me to retrieve the userID and pass it down to child components for use.
export class TransactionsComponent implements OnInit {
userID;
constructor(private store: Store<AppState>, private spinner: NgxSpinnerService) {}
ngOnInit() {
this.spinner.show();
this.store.select('user').subscribe(
user => { if (user) { this.userID = user.uid; } }
);
}
}
However, when navigating back to the Dashboard
and then returning to the Transactions
page, I encounter an issue where the user ID does not resolve, leading to an endless loading spinner.
Furthermore, upon transitioning from the transactions page to the dashboard, the subscription within the Sidebar
component is lost.
export class SidebarComponent implements OnInit {
user$: Observable<User>;
constructor(public auth: AuthService, private store: Store<AppState>) {}
ngOnInit(): void {
this.user$ = this.store.select('user');
this.store.dispatch(new userActions.GetUser());
}
}
To address this challenge, here is the effect responsible for retrieving the user ID:
@Effect()
getUser: Observable<Action> = this.actions.pipe(
ofType(userActions.GET_USER),
map((action: userActions.GetUser) => action.payload ),
switchMap(payload => this.afAuth.authState),
delay(2000), // This delay can be removed, used only for loading spinner
map( authData => {
if (authData) {
const user = new User(authData.uid, authData.displayName);
return new userActions.Authenticated(user);
} else {
return new userActions.NotAuthenticated();
}
}),
catchError(err => of(new userActions.AuthError()) )
);
I anticipate that the Transactions
component will retain the user ID state and avoid triggering the loading spinner unnecessarily during subsequent navigations.