[英]How to change a promise with async await function to observable?
I have a Nestjs rest server with a controller and a service. 我有一个带有控制器和服务的Nestjs Rest服务器。
In my controller, there is the get function, when someone makes a get request: 在我的控制器中,当有人发出get请求时,存在get函数:
@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. 不能将Promise强制转换为Observable。 Create an observable with
Observable.from()
method ( docs ). 使用
Observable.from()
方法创建一个可观察对象( docs )。
getAllFoos(): Observable<foos[]> {
return Observable.from(this.fooModel.find().exec());
}
rxjs versions < 6: rxjs版本<6:
getAllFoos(): Observable<foos[]> {
return Observable.fromPromise(this.fooModel.find().exec());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.