I need help to improve my code on Angular 7 Guard. I think its not a good practice to first subscribe to the current User to use it after on the switchMap. In advance, thank you for your help.
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { User } from '@app/core/models/user/user';
import { select, Store } from '@ngrx/store';
import * as fromRoot from '@redux/app.reducers';
import * as invoiceActions from '@redux/payment/subscription/invoice/invoice.actions';
import * as fromSubscription from '@redux/payment/subscription/subscription.reducer';
import * as fromUser from '@redux/user/user.reducers';
import { Observable, of } from 'rxjs';
import { filter, switchMap, take, tap } from 'rxjs/operators';
@Injectable()
export class LoadSubscriptionInvoicesGuard implements CanActivate {
constructor(private store: Store<fromRoot.AppState>) {
}
getFromAPI(user: User): Observable<any> {
return this.store.pipe(
select(fromSubscription.selectInvoiceLoaded),
tap((loaded: boolean) => {
if (!loaded) {
this.store.dispatch(new invoiceActions.LoadCollection(user));
}
}),
filter((loaded: boolean) => loaded),
take(1));
}
canActivate(): Observable<boolean> {
let user : User;
this.store.pipe(select(fromUser.selectCurrentUser),
take(1))
.subscribe((_user: User) => user = _user);
return this.getFromAPI(user).pipe(
switchMap(() => of(true)));
}
}
It's not a bad practice, but your code is not the best for that.
canActivate(): Observable<boolean> {
return this.store.pipe(
select(fromUser.selectCurrentUser),
switchMap(user => this.getFromAPI(user)),
map(value => !!value),
take(1),
);
}
Try avoiding splitted observables : they're asynchronous operations to begin with, which means the result of the second observable might change at a given time. By chaining them like this, you prevent those kind of side effects from happening.