I have a Nestjs rest server with a controller and a service.
In my controller, there is the get function, when someone makes a get request:
@Get()
getAllFoos() {
return this.fooService.getAllFoos();
}
In my service, there is this function to get the documents from a database
async getAllFoos(): Promise<foos[]> {
try {
return await this.fooModel.find().exec();
} catch(e) {
return e;
}
This works! I now need to change this to make it work with observables. I changed the controller to:
@Get()
getAllFoos() {
this.fooService.getAllFoos().subscribe(
response => {
console.log(response);
},
error => {
console.log(error);
},
() => {
console.log('completed');
});
}
And the service to this:
getAllFoos(): Observable<foos[]> {
try {
this.fooModel.find().exec();
} catch(e) {
return e;
}
}
The error I get is
[Nest] 7120 - 2019-2-20 15:29:51 [ExceptionsHandler] Cannot read property 'subscribe' of undefined +4126ms
The error comes from
this.fooService.getAllFoos().subscribe(
this line from the controller. I really have no clue, what to change to make it work now.
Any help or idea is appreciated!
A Promise can not be cast as Observable. Create an observable with Observable.from()
method (docs).
getAllFoos(): Observable<foos[]> {
return Observable.from(this.fooModel.find().exec());
}
rxjs versions < 6:
getAllFoos(): Observable<foos[]> {
return Observable.fromPromise(this.fooModel.find().exec());
}