我为我的角度应用程序创建了一个服务,如下所示:
export class AuthService {
public currentUser: Subject<firebase.User> = new Subject();
public currentUserId: Subject<string> = new Subject();
constructor(private auth: AngularFireAuth){
auth.authState.subscribe(r => {
this.currentUser.next(r); // the user object
this.currentUserId.next(r.uid); // the user id
});
}
}
发生路由时,我会在组件中使用此服务。
当用户首次从其浏览器到达页面时,将成功向其他组件通知身份验证更改。但是,当用户单击链接转到另一个页面时,两个可观察对象不会触发,并且不会向认证组件通知身份验证状态更改。唯一的工作方法是用户刷新浏览器,因为它们似乎仅在用户仅登陆其首页时才触发。之后,我丢失了用户信息,再也没有得到通知。
每次页面导航发生时,如何使这两个可观察对象触发?还是这样做的正确方法?
答案 0 :(得分:0)
我不知道在路由过程中使用它的原因...我在上一个项目中使用了CanLoad
//Inside Auth Service
public authStates = new BehaviorSubject<AuthState>(this.getAuthState());
private getAuthState(): AuthState {
const token = this.getToken();
if (token || !tokenHelper.isTokenExpired(token)) {
const payload: JwtPayload = jwt(token);
return {
authenticated: true,
id: payload.uid,
role: payload.type
};
}
return {
authenticated: false
};
}
canLoad(route: Route): Observable<boolean> {
const roles: string[] = route.data.roles;
return this.authState.pipe(
take(1),
map((authState: AuthState) => {
if (
authState.authenticated &&
authState.role &&
roles.includes(authState.role)
) {
return true;
} else if (!authState.authenticated && roles.includes("guest")) {
return true;
}
this.toastrService.error(
"You have not sufficient permissions for that action"
);
return false;
})
);
}
// In routes module
const appRoutes: Routes = [
{
path: environment.settings.user.backendPath,
loadChildren: "app/user/user.module#UserModule",
canLoad: [AuthService],
data: {
roles: ["user"]
}
},
]
我还使用了canActivate,canActivateChild和自定义的书面auth指令,例如* hideForRoles,* showForRoles,authOnly等...
答案 1 :(得分:0)
这是解决方案,这要感谢@DeborahK链接到angularfirebase.com:
export class AuthService {
public currentUser: Observable<UserDoc>;
constructor(
public afAuth: AngularFireAuth
) {
this.currentUser = this.afAuth.authState;
// then other components subscribe to this observable
// and can run `.id` on the resolved parameter.
}
}