[英]RXJS6 - return an Observable from a Promise function which returns an Observable?
I have a method getData
which returns an Observable<SupportingDocument>
. 我有一个方法getData
,它返回一个Observable<SupportingDocument>
。
( code and return value can't be changed as it's an external API ). ( 因为它是外部API,所以无法更改代码和返回值 )。
getData(): Observable<SupportingDocument> {
return of(new SupportingDocument());
}
When a user clicks a button , we actually show him a Modal page . 当用户单击按钮时,我们实际上会向他显示一个“模态”页面。 When that modal is closed ( Promise api) - we should call getData()
and return the value : 当该模式关闭时(Promise api)-我们应该调用getData()
并返回值:
public dialogShow(): Promise<Observable<SupportingDocument>> {
return Promise.resolve(1).then(() => { //modal was closed
return this.getData();
})
}
At the end , I should provide a method show()
which should return the value(and errors) that returned from return this.getData();
最后,我应该提供一个show()
方法,该方法应该返回从return this.getData();
返回的值(和错误return this.getData();
( shows()'s return value doesn't have to be an Observable , it can be a promise too ). ( shows()的返回值不必是Observable,也可以是一个promise )。
So I did this : 所以我这样做了:
public show(): Observable<SupportingDocument> {
return new Observable<SupportingDocument>((obs) => {
this.dialogShow().then((res: Observable<SupportingDocument>) => obs.next(res), (res) => obs.error(res));
})
}
Complete code : 完整的代码:
//user starts here
public show(): Observable<SupportingDocument> {
return new Observable<SupportingDocument>((obs) => {
this.dialogShow().then((res: Observable<SupportingDocument>) => obs.next(res), (res) => obs.error(res));
})
}
public dialogShow(): Promise<Observable<SupportingDocument>> {
return Promise.resolve(1).then(() => {
return this.getData();
})
}
getData(): Observable<SupportingDocument> {
return of(new SupportingDocument());
}
Question 题
I think I've over-complicated such a simple task. 我想我已经把这样一个简单的任务复杂化了。 More - I really don't like the new Observable
constructor approach. 更多-我真的不喜欢new Observable
构造方法。
Can this problem be solved without using the observable constructor ( including error handling) solution ? 如果不使用可观察的构造函数(包括错误处理)解决方案,是否可以解决此问题?
Why don't just wrap the Promise
into an Observable
(so that you can use all the operators an Observable
can provide) , and then use a switchMap()
? 为什么不只将Promise
包装到Observable
(以便您可以使用Observable
可以提供的所有运算符) ,然后使用switchMap()
呢?
public dialogShow(): Observable<SupportingDocument> {
return from(Promise.resolve(1)).pipe(switchMap(() => this.getData()));
}
Working StackBlitz 工作StackBlitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.