Reputation: 148624
I have a method getData
which returns an Observable<SupportingDocument>
.
(code and return value can't be changed as it's an external 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 :
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();
( shows()'s return value doesn't have to be an Observable , it can be a promise too).
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.
Can this problem be solved without using the observable constructor ( including error handling) solution ?
Upvotes: 0
Views: 1695
Reputation: 8478
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()
?
public dialogShow(): Observable<SupportingDocument> {
return from(Promise.resolve(1)).pipe(switchMap(() => this.getData()));
}
Working StackBlitz
Upvotes: 3