我有我的AuthService,我在其中订阅了authState。
@Injectable()
export class AuthService {
private user: User = null;
constructor(private afAuth: AngularFireAuth) {
const sub$ = this.afAuth.authState.subscribe(auth => {
this.user = auth;
});
get userId(): string {
return this.user.uid;
}
}
现在在其他组件中,我要获取的对象属于当前登录的用户,因此我创建了一个服务:
@Injectable()
export class SomeService{
constructor(private readonly afs: AngularFirestore,
private auth: AuthService) {
}
...
getByCurrentUser(): Observable<any> {
return this.afs.collection<any>('my-path',
ref => ref
.where('userId', '==', this.auth.userId)).valueChanges();
}
}
在组件中,我订阅了此方法:
...
ngOnInit() {
this.getData();
}
private getData(): void {
this.testService.getByCurrentUser().subscribe(
res => console.log(res),
error => console.log(error)
);
}
问题:
当我在页面之间重定向时,它可以正常工作,但是在刷新页面getData()
之后调用authState
回调之前,先分配当前身份验证,实际上userId()
方法将返回null。
如何预防?
答案 0 :(得分:2)
您可以使用auth guard或resolver,如下所示:
此保护措施将阻止加载路由,除非对用户进行身份验证。
export class AdminAuthGuard implements CanActivate {
constructor(private auth: AngularFireAuth) {}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
return this.auth.authState.pipe(map((auth) => {
if (!auth) {
// Do stuff if user is not logged in
return false;
}
return true;
}),
take(1));
}
}
在路由模块中使用它:
{
path: 'yourPath',
component: YourComponent,
canActivate: [AdminAuthGuard],
}
或,此解析器将在加载路由之前设置当前用户ID:
export class UserIdResolver implements Resolve<boolean> {
constructor(
private auth: AngularFireAuth,
private authService: AuthService,
) {}
resolve(): Observable<boolean> {
return this.auth.user.pipe(map((user) => {
if (user) {
this.authService.setCurrentUser(user.uid); // set the current user
return true;
}
this.authService.setCurrentUser(null);
return false;
}), take(1));
}
}
在路由模块中使用它:
{
path: 'yourPath',
component: YourComponent,
resolve: [UserIdResolver],
runGuardsAndResolvers: 'always',
}