我正在尝试制作一个Auth服务。 我正在使用这个:
@Injectable()
export class AuthService {
authState: any = null;
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router:Router) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth;
});
}
// Returns true if user is logged in
get authenticated(): boolean {
return this.authState !== null;
}
即使用户已登录,authenticated()函数仍然会给我错误。
当我在构造函数中控制aut.State(this.authState)时,我得到一个值,但在构造函数之外,this.authState为null。我做错了什么?
答案 0 :(得分:0)
更好的方法是拥有单独的功能
authenticated(): Observable<User> {
return this.afAuth.authState;
}
然后在您的组件中,您可以订阅此方法,就像您在服务构造函数中所做的那样
编辑!
答案 1 :(得分:0)
为什么需要使问题复杂化
在您需要值的组件中执行此操作
authState : boolean;
constructor(private afAuth: AngularFireAuth) {
this.afAuth.authState.subscribe((auth) => {
this.authState = ( auth !== null ) ? true : false;
});
}
答案 2 :(得分:0)
您可以使用 APP_INITIALIZER 等待异步操作完成。请检查以下代码:
AuthService.ts
@Injectable()
export class AuthService {
authState: any = null;
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router:Router) {
}
loadValue(){
return new Promise((resolve, reject) => {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth;
resolve(true);
});
});
}
// Returns true if user is logged in
get authenticated(): boolean {
return this.authState !== null;
}
}
app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
@NgModule({
//...
providers: [AuthService,
{
provide: APP_INITIALIZER,
useFactory: (authService: AuthService) => () => authService.loadValue(),
deps: [AuthService],
multi: true
}]
///....
})
希望它有所帮助!!