How to change a promise with async await function to observable?

问题: 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() { re...

问题:

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!


回答1:

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());
}
  • 发表于 2019-02-21 18:54
  • 阅读 ( 217 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除