如何使用 authStateChange$ 放大服务 guard.ts
How to use authStateChange$ amplifyService guard.ts
我正尝试在 guard.ts
中使用放大服务订阅 AWS Cognito 身份验证的状态更改
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 => {
})
}
}
订阅身份验证状态引用自订阅身份验证状态更改
VS 代码编辑器抛出错误。
Type 'Subscription' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'
使用 map
而不是 subscribe
。 route guard 期望 boolean
、Observable<boolean | urlTree>
、Promise<boolean | urlTree>
根据您的 rxjs 版本,您可能必须使用 pipe
方法来使用地图。如果
你的 rxjs 是 5.5+
然后像这样使用它:
return this.amplifyService.authStateChange$.pipe(
map(authSate => {
// do your logic here
})
)
如果你有一个较低的 rxjs
版本,那么使用它:
return this.amplifyService.authStateChange$.map(authSate => {
// do your logic here
})
在此处查看工作示例:https://stackblitz.com/edit/angular-8dyxaw?file=src%2Fapp%2Fapp.component.ts
如果您不想订阅守卫的状态变化,而只是想知道用户是否存在(并且已经通过身份验证),那么这个可行:
return Auth.currentAuthenticatedUser().then(user => {
if (user) {
return true;
} else {
return false;
}
});
我正尝试在 guard.ts
中使用放大服务订阅 AWS Cognito 身份验证的状态更改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 => {
})
}
}
订阅身份验证状态引用自订阅身份验证状态更改
VS 代码编辑器抛出错误。
Type 'Subscription' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'
使用 map
而不是 subscribe
。 route guard 期望 boolean
、Observable<boolean | urlTree>
、Promise<boolean | urlTree>
根据您的 rxjs 版本,您可能必须使用 pipe
方法来使用地图。如果
你的 rxjs 是 5.5+
然后像这样使用它:
return this.amplifyService.authStateChange$.pipe(
map(authSate => {
// do your logic here
})
)
如果你有一个较低的 rxjs
版本,那么使用它:
return this.amplifyService.authStateChange$.map(authSate => {
// do your logic here
})
在此处查看工作示例:https://stackblitz.com/edit/angular-8dyxaw?file=src%2Fapp%2Fapp.component.ts
如果您不想订阅守卫的状态变化,而只是想知道用户是否存在(并且已经通过身份验证),那么这个可行:
return Auth.currentAuthenticatedUser().then(user => {
if (user) {
return true;
} else {
return false;
}
});