Dealing with numerous errors from various asynchronous pipes in angular - a comprehensive guide

I am facing an issue with 2 mat-select elements in my component, both of which utilize the async pipe:


    <div class="flex-col">
        <mat-label>Issue Desc
        </mat-label>
        <mat-form-field>
            <mat-select [(value)]="model.issue_Desc" 
                [(ngModel)]="model.issue_Desc"
                name="issue_Desc" required>
                <mat-option *ngFor="let issues of (this.IssueObs$ | async)" 
                    [value]="issues.issueDesc">
                    {{issues.issueDesc}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
    <div class="flex-col">
        <mat-label>Area Desc</mat-label>
        <mat-form-field>
            <mat-select [(value)]="model.area_Desc" 
                        [(ngModel)]="model.area_Desc"
                name="area_Desc" required>
                <mat-option *ngFor="let area of (this.AreaObs$ | async )" 
                        [value]="area.areaDesc">
                    {{area.areaDesc}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>

Upon encountering a JWT token expiration on my website, the component triggers two instances of 401 Unauthorized errors. This results in difficulty for me as I face duplicate messages when redirecting the user to the login screen along with a "Session Ended" toaster message due to handling within my interceptor.

Below is my interceptor code snippet:

    intercept(request: HttpRequest<unknown>, next: HttpHandler): 
            Observable<HttpEvent<unknown>> {
        return next.handle(request).pipe(
            timeout(10000),
            catchError(error => {
                if (error) {
                    switch (error.status) {             
                        case 401: 
                            if (error.error == null) { 
                                //This section executes upon token expiry

                                this.toastr.info("Session has ended!")
                                //<<---- Executed twice
              
                                this.accountService.logout();
                            }
                            else {
                                this.toastr.error(error.error)
                            }

                            this.dialogRef.closeAll();
                            this.router.navigateByUrl('')

                            break;
                    }
                }
                return throwError(error);
            })
        );
    }

https://i.sstatic.net/tGnUd.png

https://i.sstatic.net/1gudI.png

I need guidance on how to handle these errors efficiently to display only one message even in the presence of multiple errors originating from the async pipe? Any assistance would be highly appreciated. Thank you in advance.

Answer №1

The reason for receiving multiple requests is because the intercept function is triggered multiple times, and pipe operators are running in parallel.

Requests are not passing through the same shared pipe, so each pipe() is processing one request at a time.

You can set up a subscription in the Interceptor to handle errors as they occur and then apply throttleTime or distinctUntilChanged.

@Injectable()
export class I1 implements HttpInterceptor {

constructor() {
  this.errorLog$ = new Subject();
  this.errorLog$
  .pipe(throttleTime(2000)) // all errors will go through this pipe sequentially
  .subscribe(e => console.log('log:', e));
}

private errorLog$ : Subject<any>;

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> { // triggered for each individual request

return next.handle(req).pipe( // each request creates its own separate pipe
catchError((e) =>
{
this.errorLog$.next(e); // send error to a single observer
throw e;
}
)
);
}
}


 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display Dynamic Information According to Query Parameters in Angular

Is it possible to use query parameters in Angular to filter out data? I have an array called this.rows and I want to only display the rows that match the query parameter "Pending". How can I achieve this using queryParams? Below is my code snippet: // t ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Issue with importing in VueJS/TypeScript when using gRPC-Web

I have developed a straightforward VueJS application and am currently grappling with incorporating an example for file upload functionality. The proto file I am utilizing is as follows: syntax = "proto3"; message File { bytes content = 1; } ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

InitAuth0 Auth0 encountering deepPartial error in Next.js with TypeScript setup

Having some trouble setting up auth0 with nextjs using typescript. When I try to initialize Auth0, I encounter an error regarding deep partials, Argument of type '{ clientId: string; clientSecret: string; scope: string; domain: string; redirectUri: st ...

Exploring the DynamoDB List Data Type

Currently, I am working on an angular 8 application where I have chosen to store JSON data in a list data type within DynamoDB. Inserting records and querying the table for data has been smooth sailing so far. However, I have run into some challenges when ...

Convert angular-tree-component JSON into a suitable format and dynamically generate checkboxes or radio buttons

Currently, I am using the angular-tree-component for my treeview implementation. You can find more details about it in this reference link. The array structure I am working with is as follows: nodes = [ { id: 1, name: 'root1', ...

The risk of a race condition could arise when working with nested switchMaps in ngr

I am currently working on an Angular 9 application that heavily relies on observables. In a specific component, I have the following requirements: Retrieve all companies to access certain information. Fetch all responses and link additional company detai ...

Changing md-sidenav mode in Angular Material 2

Looking to modify the behavior of the md-sidenav in Angular Material 2, switching from side on desktops to over on mobile devices. Is there a method to achieve this programmatically? Appreciate any guidance! ...

Issue with passing an Angular or Ionic object to a view

Currently facing an access issue in my home.ts file where I am unable to retrieve object values in home.html using {{detail.ID}} senddata(){ this.httpClient.get('http://queenstshirtdesigner.com/wp-json/posts/'+this.id, { header ...

What advantages does incorporating observables into Angular 5 HTTP requests offer?

I have been struggling with understanding how to use httpclient in angular 5. As a newcomer to Angular, I am currently following the official angular tutorial but find myself lacking knowledge about observables, promises, pipes, and more. At the moment, I ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

What are the steps to customize the collapse and expand icons?

Having trouble changing the icon up and down when collapsing and expanding with the code below. <div class="attach-link"> <a href="javascript:void(0);" *ngIf="fileData.fileDataType.canAttach && !isFinancialEntity" (click) ...

What is the best way to showcase the Observable information I receive from calling my api with Angular?

Just beginning my journey with Angular, I am on a quest to create a simple app that showcases a catalog of products. In my TypeScript file, I have a getProducts() function that calls an API and returns an observable list of products consisting of attribute ...

Experiencing a challenge while attempting to integrate AWS Textract with Angular using the aws-sdk/client-textract npm package. Despite my efforts, I keep encountering a Credentialerror

I have set up aws-sdk/client-textract in my app.component.ts file and specified the region for my Textract service. However, I am unsure of where to provide my access_key and secret_key, as well as what parameters need to be passed for Textract. If anyone ...

What is the best way to convert JSON into a complex object in Typescript and Angular?

In my Typescript class for an Angular version 5 project, I have a JavaScript function that generates a style object. Here is the function: private createCircle(parameters: any): any { return new Circle({ radius: parameters.radius, ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Output the initial value and subsequently disregard any values emitted during a specified time interval

Check out my code snippet: app.component.ts notifier$ = new BehaviorSubject<any>({}); notify() { this.notifier$.next({}); } app.component.html <div (scroll)="notify()"></div> <child-component [inp]="notifier$ | async" /> ...

Is there a way for a function to be executed without being detected by surveillance?

Here's the Component I'm working with: @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignUpComponent implements OnInit ...