从服务获取数据

问题描述 投票:0回答:1

我有以下服务

@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()函数时返回它

angular
1个回答
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;
  }

}

判决书

  1. 只需订阅该活动即可第一时间收到通知
  2. 并使用getter或方法,以便稍后检查用户的可信度
© www.soinside.com 2019 - 2024. All rights reserved.