[英]How to return a promise inside Observable subscriber angular 8
I am working on an angular 8 project and I need to return a promise inside a subscribe.我正在处理一个 angular 8 项目,我需要在订阅中返回一个承诺。 Here is my observable:这是我的观察:
export async function resolvePage(api: ApiService, transition: Transition) {
const slug = transition.params().slug.split('/').slice(-1).pop();
return api.get(`/pages/${slug}`).toPromise();
}
And I need to do something like this, but it doesn't work:我需要做这样的事情,但它不起作用:
export async function resolvePage(
api: ApiService,
transition: Transition,
stateService: StateService
) {
const slug = transition
.params()
.slug.split("/")
.slice(-1)
.pop();
return api.get(`/pages/${slug}`).subscribe(
(res: any) => {
return new Promise((resolve, reject) => {
resolve(res);
});
},
() => {
stateService.go("app.404");
}
);
}
How can I do it?我该怎么做?
You can use Observable.toPromise()
method.您可以使用Observable.toPromise()
方法。 See https://www.learnrxjs.io/operators/utility/topromise.html见https://www.learnrxjs.io/operators/utility/topromise.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.