Currently, I am utilizing an API-service that delivers an Observable containing an array of elements.
apiMethod(input: Input): Observable<ResultElement[]>
Typically, I have been selecting the first element from the array, subscribing to it, and then using that specific element to navigate to another page in this manner:
this.apiService
.apiMethod(input)
.pipe(map((results) => results[0])
.subscribe(
(result) => {
return this.router.navigate('elements/', result.id)
}
)
This method has been successful thus far.
However, my goal is not merely to use the first element. Instead, I would like a MatDialog or similar popup to appear, allowing the user to select which element to proceed with before routing to the appropriate one.
In cases where the list contains only one element, the dialog should be omitted, and the user should be routed immediately.
I attempted to implement a dialog within the .pipe(map())
function but encountered issues as the subscribe()
occurs before receiving the user's response, leading to failure. I am uncertain if this approach is correct. How would you go about solving this dilemma?
Edit I partially followed @BizzyBob's suggestion:
By substituting map with switchmap in the API-call, the code looks like this:
this.apiService
.apiMethod(input)
.pipe(switchMap((results) => this.mapToSingle(results))
.subscribe(
(result) => {
return this.router.navigate('elements/', result.id)
}
)
The mapToSingle(ResultElement[])
function is structured as follows:
private mapToSingle(results: ResultElement[]): Observable<ResultElement> {
if (results.length === 1){
return of(results[0]);
}
const dialogConfig = new MatDialogConfig<ResultElement[]>();
dialogConfig.data = results;
const dialogRef = this.dialog.open(ResultDialogComponent, dialogConfig);
return dialogRef.afterClosed();
}