我有以下服务
@Injectable()
export class AdminCheckService {
isAdmin: boolean;
uid: string;
constructor(private authService: AuthService, private db: AngularFireDatabase)
{
this.authService.user.subscribe(
(auth) => {
if (auth == null) {
console.log('Not Logged in.');
} else {
this.uid = auth.uid;
}});
db.object('/ownership/questions/' + this.uid ).subscribe( checks => {
this.isAdmin = checks.admin;
console.log(this.isAdmin);
});
}
getAdmin() {
return this.isAdmin;
}
}
当我注入服务并调用getAdmin()函数时,我得到一个未定义的值。我假设这是因为我有一个异步调用服务器,在调用getAdmin()函数之前没有返回。我怎样才能让它等待isAdmin获得一个值并返回?
编辑:这看起来类似于如何从异步调用返回,但它引用直接从异步调用返回值。我想要完成的是将该值存储在变量中,然后在调用getAdmin()函数时将其返回
答案 0 :(得分:0)
事件发射器是您在异步通知中最好的朋友
import {
EventEmitter
} from "@angular/core";
@Injectable()
export class AdminCheckService {
// Use Event Emitters initially
onUserPriviledgeIdentified: EventEmitter < boolean > = new EventEmitter < boolean > ();
// It can be used later on
isAdmin: boolean;
uid: string;
constructor(private authService: AuthService, private db: AngularFireDatabase) {
this.authService.user.subscribe(
(auth) => {
if (auth == null) {
console.log('Not Logged in.');
} else {
this.uid = auth.uid;
}
});
db.object('/ownership/questions/' + this.uid).subscribe(checks => {
this.isAdmin = checks.admin;
console.log(this.isAdmin);
// Emit your findings
this.onUserPriviledgeIdentified.emit(checks.admin);
});
}
// Won't work for the first time, later it's useful
getAdmin() {
return this.isAdmin;
}
}
判决