Joe Berthelot
Joe Berthelot

Reputation: 735

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?

Upvotes: 0

Views: 6406

Answers (2)

Joshua Ohana
Joshua Ohana

Reputation: 6141

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

Upvotes: 3

omeralper
omeralper

Reputation: 10114

if you use @angular/http your http requests should return rxjs/Observable. And once you subscribe it, it returns subscription. You cannot resubscribe the subscription class.

import {Observable} from "rxjs";
@Injectable()
export class MyService() {

    public userFName;
    getUserInfoPromise():Observable<MyResponseType> {
        let someObservable = this.someApi.someRequestPOST(request).mergeMap((response:MyResponsType) => {
         //you can process the response data here before components use it
              this.userFName = response.userFName;
              return new Promise(resolve => resolve(response));
         });
         return someObservable;
    }
}

And in your component, just join the subscription chain in this way.

 this.myService
            .getUserInfoPromise(requestData)
            .subscribe(
                (res: MyResponseType) => {

                }, (error) => {

                });

Upvotes: 0

Related Questions