3

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!

Mark
  • 2,061
  • 1
  • 16
  • 26
Klaxx
  • 380
  • 1
  • 6
  • 22
  • In the service inside try{} don’t you need a return statement similar to your catch{}.. – estinamir Feb 20 '19 at 14:58
  • I tried that. My IDE is marking the line red then with this message: "Type 'Promise' is missing the following properties from type 'Observable': _isScalar, soure, operator, lift and 6 more. – Klaxx Feb 20 '19 at 15:03
  • I dont know why it expects a promise still?! – Klaxx Feb 20 '19 at 15:04
  • 1
    What about not using observable as shown here https://stackoverflow.com/a/54770820/10634638 – estinamir Feb 20 '19 at 15:46

1 Answers1

5

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());
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56