Reputation: 113
I want to use gRPC service to communicate between my microservices. but when getting a response from Grpc service, before return a method, I want to do some modification and functionality.
sample project: https://github.com/nestjs/nest/tree/master/sample/04-grpc
like this:
@Get(':id')
getById(@Param('id') id: string): Observable<Hero> {
const res: Observable<Hero> = this.heroService.findOne({ id: +id });
console.log(res); res.name = res.name + 'modify string';
return res;
}
but show below message in console.log instead of the original response.
Observable { _isScalar: false, _subscribe: [Function] }
Upvotes: 5
Views: 5354
Reputation: 24555
One way to do this is to convert your Observable
to a Promise
using e.g. lastValueFrom
and await this promise. You can then modify and return the result:
@Get(':id')
async getById(@Param('id') id: string): Promise<Hero> {
const res:Hero = await lastValueFrom(this.heroService.findOne({ id: +id }));
res.name = res.name + 'modify string';
return res;
}
Note: If you want to stick to Observable
use bharat1226's solution.
Upvotes: 13
Reputation: 159
Your can use map operator to transform the emitted value.
In the below code, you are adding string modify string
to name
.
@Get(':id')
getById(@Param('id') id: string): Observable<Hero> {
return this.heroService
.findOne({ id: +id })
.pipe(map(item => ({ ...item, name: `${item.name}modify string` })));
}
If any time, you want to log emitted values or perform side effects in an Observable stream, you can use tap operator
@Get(':id')
getById(@Param('id') id: string): Observable<Hero> {
return this.heroService
.findOne({ id: +id })
.pipe(tap(item => console.log(item)));
}
Upvotes: 3