-3

I want to return a string from a service searching in firebase. But the return in my component is "undefined" while in the service, inside the ".subscribe" it's a normal string return. Do you have any idea ?
img1 : order.service.ts
img2 : user-orders.component.ts
console
More than that in the user-orders.component.ts I have create a "userId: string;" in the class

1 Answers1

0

You have to return a promise from the service:

import { map } from 'rxjs/operators';
....
async getUserIdOfFeeder(db: AngularFirestore, id: string): Promise<string> {
  // don't forget this return statement
  return db.collection('feeder')
           .doc<Feeder>(id)
           .valueChanges()
           // map the response
           .pipe(map((data) => data.userId))
           // convert the observable into a promise
           .toPromise();
}

Then you should be able to read it as a promise.

That being said, I would use Observables because they are more powerful.

getUserIdOfFeeder(db: AngularFirestore, id: string): Observable<string> {
  // return same thing as above but don't tack on a .toPromise()
}

And then to read it, it would be this.orderService.getUserIdOfFeeder(this.db, id).subscribe(res => console.log(res));

AliF50
  • 16,947
  • 1
  • 21
  • 37
  • Thank you very much for your time and your help ! I'm trying to learn the operation of those 2 different method, do you have a link to recommend me ? – Franck Gomez May 22 '21 at 21:08
  • https://stackoverflow.com/questions/36777284/angular-2-convert-observable-to-promise. That's a link on how to convert to a promise. For other Rxjs operators, just try to use them as much as possible. The most important are map, filter, switchMap and maybe combineLatest. https://www.learnrxjs.io/learn-rxjs/operators/transformation/map You can learn them from that source or any other blog post. – AliF50 May 23 '21 at 01:11