I've been working on implementing authGuard in my app, but I keep encountering an error.
Below is the guard implementation:
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
/**
* Returning an observable of type boolean is the correct way to handle canActivate that needs to wait for an observable result.
*/
// 1. Select the authConfig from the store
return this.getAuthentication()
.pipe(
// 2. Take the first instance.
take(1),
// 3. Map the observable to an observable of type boolean
// !! turns the value into a boolean
map((auth: AuthConfig) => !!(auth && auth.success === true)),
// 4. If not authenticated then redirect the user.
tap((auth: boolean) => this.redirectUserIfUnauthenticated(auth, this.getRedirectUrl(route))),
// Catch any errors and handle them.
catchError((...args) => this.handleError.apply(this, args))
)
}
This is the getAuthentication function:
private getAuthentication(): Observable<AuthConfig> {
return zip(
this.store.select(ngrxTypes.authConfig),
this.store.select(ngrxTypes.optionsConfig)
).pipe(
mergeMap((configurations: [AuthConfig, OptionsConfig]) => this.getAuthenticationStatus(configurations)),
mergeMap((authConfig: AuthConfig) => this.setAuthenticationStatus(authConfig))
);
}
Here's where the HTTP get method is performed:
private getAuthenticationStatus([auth, config]: [AuthConfig, OptionsConfig]): Observable<AuthConfig> {
if (auth) {
return this.store.select(ngrxTypes.authConfig);
} else {
const token = this.storageService.getCookie('token');
const apiUrl = `${environment.user_profile_domain_url || config.user_profile_domain_url}/widgets/api/auth`;
if (config && token) {
return this.http.get(apiUrl, this.storageService.getHeader('Bearer', token))
.map(login => login.json())
} else {
this.store.dispatch(this.authActions.setAuthConfig({success: false}));
return this.store.select(ngrxTypes.authConfig);
}
}
}
Despite following the process, I consistently face this error and I'm unsure of the reason behind it.