Reputation: 376
I am trying to subscribe to the state changes for AWS Cognito authentication using amplify service in guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AmplifyService } from 'aws-amplify-angular';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor( private amplifyService: AmplifyService ) {
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.amplifyService.authStateChange$.subscribe(authSate => {
})
}
}
Subsribe to auth states refered from Subscribe to Authentication State Changes
VS code editor throws an error.
Type 'Subscription' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'
Upvotes: 1
Views: 2340
Reputation: 806
If you don't want to subscribe to the state change in your guard, but instead just want to know if the user exists (and has been authenticated), then this works:
return Auth.currentAuthenticatedUser().then(user => {
if (user) {
return true;
} else {
return false;
}
});
Upvotes: 1
Reputation: 12970
Use map
instead of subscribe
. A route guard expects a boolean
, Observable<boolean | urlTree>
, Promise<boolean | urlTree>
Depending on your rxjs version you may have to use pipe
method to use map. If
your rxjs is 5.5+
then use it like:
return this.amplifyService.authStateChange$.pipe(
map(authSate => {
// do your logic here
})
)
If you have a lesser rxjs
version then use it like:
return this.amplifyService.authStateChange$.map(authSate => {
// do your logic here
})
See a working sample here: https://stackblitz.com/edit/angular-8dyxaw?file=src%2Fapp%2Fapp.component.ts
Upvotes: 2