0

I have the following service

@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;
}

}

When I inject the service and call the getAdmin() function I get an undefined value. I am assuming this is because I have an asynchronous call to the server that does not return before the getAdmin() function is called. How can I make it so that I can make it wait for isAdmin to have a value and return?

Edit: This may seem similar to the How to return from an asynchronous call but it refers to return the value directly from the async call. What I'm trying to accomplish is storing that value in a variable and then returning it when the getAdmin() function is called

Sandy_22
  • 117
  • 1
  • 1
  • 10
strypeez
  • 175
  • 1
  • 3
  • 16
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Mar 05 '18 at 16:57

1 Answers1

0

Event Emitters are your best friends in Asynchronous Notification

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;
  }

}

Verdict

  1. Just subscribe to the event to get notified for the first time
  2. and Use a getter or a method, to check the user's credibility later on
Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24