K
K
Konstantin2020-09-07 22:11:49
Angular
Konstantin, 2020-09-07 22:11:49

How to properly handle an exception for an async pipe?

I have a method like this - which returns an observable this.applicationObswith data:

this.applicationObs = this.route.paramMap.pipe(
            filter((params) => params.has('id')),
            switchMap((params) => this.applicationService.getApplicationDetails(params.get('id'))),
            tap((response) => {
                const fabricaSidebar = fabricApplicationSidebarMenu(response.application);
                this.sidebarSections = fabricaSidebar.getSidebarMenuItems();
            }),
        );


Next in the template I do the check:



<ng-template #loading>
    <div class="loader">
        <mat-spinner [diameter]="50"></mat-spinner>
    </div>
</ng-template>


How can I catch an error, for example, if the server does not respond and display another template with an error or call alert with a message. Now - if the server does not respond - it spins endlessly
<code><ng-template #loading>
    <div class="loader">
        <mat-spinner [diameter]="50"></mat-spinner>
    </div>
</ng-template></code>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-09-07
@Junart1

You can try to make such a wrapper for requests

function requestWrapper(request) {
  return concat(
    of({
      loading: true,
      completed: false,
      value: null,
      error: null,
    }),
    request.pipe(
      map(value => ({
        loading: false,
        completed: true,
        value,
        error: null,
      })),
      catchError(error => of({
        loading: false,
        completed: true,
        value: null,
        error,
      }))
    )
  )
}

You can even issue a decorator or as an operator and make your own custom async pipe, which can only display value at once
. And all sorts of state managers usually offer their own mechanisms for obtaining the status of entities.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question