Hi i'm trying to get to grips with rxjs in angular 9 and i'm trying to make a call conditionally based on a response of an observable but can't seem to get it to work without nesting subscriptions. I have read several articles including this and this but I can't seem to resolve my issue.
In my reading I also read this SO post
The confirmed()
method in the DialogConfirmService
is triggered when a confirm button is clicked
Please note I have tried more than two refactors but the posted ones are examples of what I've been trying.
My current working solution (I want to get away from the nested subscriptions)
this.dialogConfirmService
.confirmed()
.pipe(take(1))
.pipe(map(x => {
this.isSaving = true;
return x;
})
)
.subscribe(confirmed => {
if (confirmed) {
this.myService.save('', '')
.pipe(take(1))
.subscribe(
(data) => this.onSuccess(data),
(error) => this.handleError(error)
);
}
});
My refactor failure 1
this.dialogConfirmService
.confirmed()
.pipe(take(1))
.pipe(
map(x => {
this.isSaving = true;
console.log(x);
return x;
}
),
mergeMap(cv =>
this.myService.save(
this.rulesetForm.controls.name.value,
JSON.parse(this.rulesetForm.controls.definiation.value)
)
)).subscribe(j => this.isSaving = false);
My refactor failure 2
onSave(): void {
this.dialogConfirmService
.confirmed()
.pipe(take(1))
.pipe(
flatMap(confirmed => this.onConfirm(confirmed)),
);
}
private onConfirm(confirmed: any) {
if (confirmed) {
this.isSaving = true;
this._ruleSetMapperService.save(
this.rulesetForm.controls.name.value,
JSON.parse(this.rulesetForm.controls.definiation.value)
);
} else {
return Observable.create(function(observer) {
observer.next(confirmed);
observer.complete();
});
}
}
Below is the other code that is called (for the sake of completness)
the dialog service
..other stuff...
export class DialogConfirmService {
...other stuff...
public confirmed(): Observable<any> {
return this.dialogRef
.afterClosed()
.pipe(take(1),
map(res => {
return res;
})
);
}
}
My saving service
export class MyService {
save(rsn: string, rsd: string): Observable<any> {
...other stuff... (generates the body)
return this._http.post('myUrl', JSON.stringify(body), { headers: this.headers });
}
}