0

Im trying to use from a external api in nestjs with axios.

@Injectable()
export class PIntegration {
  constructor(private httpService: HttpService) { }
  API = process.env.API || 'http://localhost:3000';
  header = { headers: { 'Content-Type': 'application/json' } };

  async getPrestacionById(id: string): Promise<Observable<IPrestacion>>{
   
    return this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data));
  }
}

And my service class looks like this:

@Injectable()
export class ProductService{
    constructor(private pIntegration: PIntegration){}
    async producto(id: string) {
        const infoPrestacion = await  this.pIntegration.getPrestacionById(id);
        console.log({ infoPrestacion })
        if (infoPrestacion)
        {
             if (infoPrestacion.detalles) {
                console.log(infoPrestacion.detalles)
                console.log("tiene detalles")
            }
        }
        return infoPrestacion;
    }
}

However if i console.log the value "infoPrestacion" this is the result:

{
  infoPrestacion: Observable {
    source: Observable { _subscribe: [Function (anonymous)] },
    operator: [Function (anonymous)]
  }
}

and it doesnt get to the second since it's not resolved yet. Is it possible to wait for the result until it's resolved (i don't have any config for the HttpModule) ? The return actually gets the object itself "infoPrestacion" but i need to work with the values and not return that object.

alex
  • 113
  • 2
  • 14
  • looks like you don't want to use rxjs obervables, then follow this https://indepth.dev/posts/1287/rxjs-heads-up-topromise-is-being-deprecated – Micael Levi Nov 23 '21 at 22:03
  • @MicaelLevi i was looking for both aproach but i solved this with "lastValueFrom" (could not see that website, server seems to be off) – alex Nov 24 '21 at 00:49

1 Answers1

1

I solved my problem with this, i hope this might fit your needs.

If you take your observable as a promise there are two solution that might fit for you.

In the class you are using an external api:

Add lastValueFrom which converts an observable to a promise by subscribing to the observable, waiting for it to complete, and resolving the returned promise with the last value from the observed stream.

firstValueFrom could be also a solution, does the opposite of lastValuefrom getting the first element as your promise is solved.

@Injectable()

export class PIntegration {
  constructor(private httpService: HttpService) { }
  API = process.env.API || 'http://localhost:3000';
  header = { headers: { 'Content-Type': 'application/json' } };

  async getPrestacionById(id: string): Promise<IPrestacion>{
   
    return lastValueFrom(this.httpService.get(`${this.API}/prestacion/${id}`, this.header).pipe(map((res) => res.data)));
  }
}
alex
  • 113
  • 2
  • 14