Home > database >  Can't get data from .pipe(map())
Can't get data from .pipe(map())

Time:04-09

Got some problems with observable. I have a function, with one returns me an Observable.

public getData(userId) {
    const data = this.execute({userId: userId});
    return {event: "data.get", data: data}
}

private execute(input: SomeDto):  Observable<SomeRefType[]> {
    return this.databaseGateway.queryMany(DatabaseCommand.WebRecordGetbyparticipantid, {
      parameters: {
        prm_contextuserid: input.userId,
        prm_filterparticipantids: null,
        prm_filtertext: null
      }
    }).pipe(map(res => res));
  }

Type what pipe(map) returns

What I'm got when trying to return or log data

Question: Why .pipe(map(res => res)) don't work? What am I doing wrong?

For sure, I can read data from .pipe(take(1)).subscribe(data => console.log(data)), but, how can I return data from construction like this?

Thanks everyone! Have a good day!

CodePudding user response:

As said in the Rxjs documentation observable are lazy computation.

It means the as long as you don't subscribe to them they won't do anything. It exists two ways to trigger a subscription.

Either within a ts file using .susbcribe() or within a view when calling an endpoint.

If you're using nestjs it would be when calling the url defined within a @Controller('') with an http verb like @Get('path')

By convention you suffix observable variables with $: data$ = new Observable<any>().

CodePudding user response:

At some point you'll have to convert the observable to a promise. Best to do it early and convert it using firstValueFrom immediately after the query. Then convert your caller to an async method to use the returned value.

public async getData(userId): Promise<{ event: string, data: SomeRefType[] }> {
  const data = await this.execute({userId: userId});
  return { event: 'data.get', data };
}

private execute(input: SomeDto):  Promise<SomeRefType[]> {
  const res$ = this.databaseGateway.queryMany(DatabaseCommand.WebRecordGetbyparticipantid, {
    parameters: {
      prm_contextuserid: input.userId,
      prm_filterparticipantids: null,
      prm_filtertext: null
    }
  });
  return firstValueFrom(res$);
}
  • Related