I need some kind of special RxJS syntax if it exists for this scenario:
this.electronicInvoiceService.getElectronicInvoice(this.invoiceId)
.subscribe(and here I can get .isApproved, for example:
(data) => data.isApproved
and what I want is IF data.isApproved is false only then
I want to subscribe to this
next observable I wrote below this);
do this next subscribe only if isApprove is false
this.electronicInvoiceStagingService.getElectronicInvoice(this.invoiceId).subscribe();
What I tried already: I tried to have some variable in in my ts file and inside subscribe I did this.myVariableName == data.isApproved but this did not work I think because subscribing takes some time and it was bad logic.
[SOLUTION]: The comment below solved it, its silly of me I didnt use it right away (: solution> Why is a simple if statement not sufficient? (data) => {if (!data.isApproved) this.electronicInvoiceService.getElectronicInvoice(this.invoiceId).subscribe();}
CodePudding user response:
Subscriptions inside other subscriptions are not considered best practices in RxJs.
I think that a more idiomatic solution could be the following
this.electronicInvoiceService.getElectronicInvoice(this.invoiceId)
// here you start a pipe, i.e. a series of operations that transform the source stream
.pipe(
// concatMap is the first operator which basically says: wait for upstream
// to notify and then take the data notified and return a new Observable
concatMap( data => {
// here you put your if logic
if (!data.isApproved) {
// return the other Observable
return this.electronicInvoiceStagingService.getElectronicInvoice(this.invoiceId)
}
// otherwise return EMPY, which is an Observable that does nothing and just
// completes immediately
return EMPTY
})
)
// eventually you just subscribe to the one and only one stream you have created
// transforming, with the pipe, the original source stream
.subscribe(dataFromStagingService => {
// do anything you need to do with the data returned by the staging service call
})