Search code examples
angulartypescriptgoogle-cloud-firestoreangularfire5

Angular / TS - How to call a function from a component to a service and get a returned value


I have a component that calls "getUserDocInfo()" which is in its own service. How would I go about calling that function and then using the returned data for further code?

My Component

 getToken(){
    this.userService.getUserDocInfo();
    // once this is called I would like to use some of the values in the returned data
  }

My Service

getUserDocInfo() {
    this.getUserInfo().then(() => {
      this.userDoc = this.afs.doc(`users/${this.userID}`);
      this.user = this.userDoc.snapshotChanges();
      this.user.subscribe(value => {
        const data = value.payload.data();
      });
    })
  }

 async getUserInfo() {
    const user = await this.authService.isLoggedIn()
    if (user) {
      this.userID = user.uid;
    } else {
      // do something else
    }
  }

Any help on best practises here would be greatly appreciated.


Solution

  • One way to do it is implementing an callback that you would pass on the method parameters. Something like this.

    getUserDocInfo(callback) {
        this.getUserInfo().then(() => {
          this.userDoc = this.afs.doc(`users/${this.userID}`);
          this.user = this.userDoc.snapshotChanges();
          this.user.subscribe(callback);
        })
      }
    
    getToken(){
        this.userService.getUserDocInfo((value) => {
            console.log(value.payload.data());
        });
      }
    

    You could return an Observable too and subscribe to it on you component context and you could handle the subscriptions as you want.

    import { Observable } from 'rxjs/Observable/';
    import 'rxjs/add/observable/fromPromise';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/mergeMap';
    
    @Injectable()
    export class AlertService {
    
      //constructor and properties...
    
      getUserDocInfo(): Observable<any> {
        Observable.fromPromise(this.getUserInfo()).mergeMap(() => {
          this.userDoc = this.afs.doc(`users/${this.userID}`);
          this.user = this.userDoc.snapshotChanges();
          return this.user.map(user => user);
        });
      }
    }
    
    @Component(...)
    export class MyComponent implements OnDestroy {
    
      subscriptions: Array<Subscription> = new Array;
    
      //constructor
    
      getToken(){
        const sub = this.userService.getUserDocInfo().subscribe((value) => {
            console.log(value.payload.data());
        });
        this.subscriptions.push(sub);
      }
    
      ngOnDestroy() {
        this.subscriptions.forEach(sub => sub.unsubscribe());
      }
    }