user3642173
user3642173

Reputation: 1255

Getting Observable value before executing function in Angular2

I have a simple simple system with a user authentication system from Firebase. I want to receive a list of data for the user currently logged in. I get the information from the currently logged in user by subscribing to an observable from Firebase.

However, the value of private authId which is set in my constructor is not called before the getAllEmails() function is called. Therefore the ${this.authId} yields undefined. How can I make sure that I have the value of authId ready from the observable before my getAllEmails function is called?

import { Injectable } from '@angular/core';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { Email } from '../email';
import { AuthService } from '../auth/auth.service';

@Injectable()
export class EmailService {

  private authId: string;

  constructor(
    private af: AngularFire,
    private authService: AuthService
  ) {
    this.authService.getUserInformation()
      .subscribe(user => {
        this.authId = user.authId;
      })
  }    

  getAllEmails(): FirebaseListObservable<any> {
    return this.af.database.list(`/emails/${this.authId}`);
  }

}

Upvotes: 1

Views: 257

Answers (1)

Kamran Pervaiz
Kamran Pervaiz

Reputation: 1931

There are couple of things you can do for this

  1. create a base service class and get authId in the constructor of base class
  2. get the authId in the constructor of Component and call getAllEmails(authId)

the solution is below:

export class baseService{

private authId: string;

  constructor(private authService: AuthService) {
    this.authService.getUserInformation()
      .subscribe(user => {
        this.authId = user.authId;
      })
  }
getAuthId(): number{
       return this.authId;
}
}

import {baseService} from '<yourPath>'

@Injectable()
export class EmailService extends baseService {

  private authId: string;

  constructor(private af: AngularFire) {  }    

  getAllEmails(): FirebaseListObservable<any> {
    return this.af.database.list('/emails/'+ super.getAuthId());
  }

}

2nd Solution would be:

instead of base class have another service class to get AuthId in controller and pass it. I think first solution is a little better.

Upvotes: 1

Related Questions