Search code examples
angularangular2-services

Angular 2 passing value from service to component


Function inside service:

getUserInfo() {
  this.af.authState.subscribe(authData => {
    let email = authData.email;
    let array = this.database.list('registeredUsers', {
      query: {
        orderByChild: 'email',
        equalTo: email
      }
    }).subscribe(data => {
      let userFName = data[0].firstName;
    });
  });
}

Component:

ngOnInit() {
    this.afService.getUserInfo();
}

The function itself works great, but how do I pass the let userFName variable to be used within the component?


Solution

  • What it sounds like you want is to make this an Injectable service. That will let you make calls into it from any Component.

    It looks best to create a new promise to return, which you can resolve once the database.list call is resolved.

    @Injectable()
    export class MyService() {
      public userFName;
    
      getUserInfo() {
        // return a new promise, which you resolve once you get the data
        return new Promise((resolve, reject) => {
          this.af.authState.subscribe(authData => {
            let email = authData.email;
            let array = this.database.list('registeredUsers', {
              query: {
                orderByChild: 'email',
                equalTo: email
              }
            }).subscribe(data => {
              let userFName = data[0].firstName;
    
              // resolve promise with username
              resolve(userFName);
            });
          });
        });
      }
    }
    

    and your component

    @Component({
        providers: [MyService]
      )
    }
    export class MyComponent {
      constructor(private myService: MyService) {
        myService.getUserInfo().then(userFName => {
          console.log('userFName =', userFName);
        });
      }
    }