What is the best way to differentiate the handling of a 401 Unauthorized response from other errors within an Angular 8 service that utilizes RxJS?

My REST API implementation requires an access token for user identification with each call. If the token is missing or expired, the endpoint returns a 401 UNAUTHORIZED response.

There are instances where I make API calls using a timer in my service class:

getFoo(id: String): Observable<Foo> {
  return this.http.get<Foo>(url, HTTP_OPTIONS);
}

getFooList(): Observable<Foo[]> {
  return timer(0, FIVE_MINUTES).pipe(
    switchMap(() => this.http.get<Foo[]>(url, HTTP_OPTIONS))
  );
}

In the component, I initialize an empty array for Foo items and call the loadFooList() method in the ngOnInit() lifecycle hook:

fooList: Foo[] = [];

ngOnInit(): void {
  this.loadFooList();
}

private loadFooList() {
  this._fooService.getFooList().subscribe(
    (fooList) =>  this.fooList = fooList,
    (err) => console.error(err)
  );
}

My concern is about handling the 401 response in the service itself rather than in each component that utilizes it. Is there a way to check for a 401 response within the service?

Answer №1

To handle authentication, I implemented an interceptor in my project.

auth.interceptor.ts

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private _router: Router,
  ) { }

  intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(httpRequest).pipe(
        catchError((error) => {
            if (error.status == 401) {
                this._router.navigate(['/login']);
            } else {
                return Observable.throw(error);
            }
        })
    );
  }
}

I then added the interceptor as a provider in my app.module.ts

@NgModule({
    providers: [{
     provide: HTTP_INTERCEPTORS,
     useClass: AuthInterceptor,
     multi: true
    },
  ],
  bootstrap: [AppComponent,]
})
export class AppModule { }

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

Eliminating the muted attribute does not result in the sound being restored

I am looking to implement a feature where a video loads automatically without sound, but when a user clicks a button labeled "Watch with Sound", the video restarts from the beginning and plays with sound. Below is the JavaScript code: let videoButton = do ...

Retrieve all services within a Fargate Cluster using AWS CDK

Is there a way to retrieve all Services using the Cluster construct in AWS CDK (example in TypeScript but any language)? Here is an example: import { Cluster, FargateService } from '@aws-cdk/aws-ecs'; private updateClusterServices(cluster: Clus ...

Populate your website with both a Bootstrap Popover and Modal for interactive user engagement through hover

Here's the situation: I want to showcase a user's name with a popover that reveals a snippet of their profile information. I've got that part down, where it dynamically generates and displays the popover content as needed. The popover functi ...

AngularJS can easily interpret and extract information from HTML code

As an example, I have dynamically generated HTML on my webpage like this: <ul> <li>Country</li> <li>State</li> <li>City</li> </ul> I am looking to send this information to the database after clicking a b ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Using jQuery, how can you make fixed elements fade as the page scrolls?

How can I make a fixed element, such as a corner ad or notice, fade when the page is scrolled down to a certain point? What would be the most effective method for determining this point: using pixels, percentage, or another way? And how can I implement th ...

What is the reason for updating only one out of three charts using react-chartjs-2?

Recently, I came across an issue with a modal that includes a text field for recording numerical values. These recorded values are then passed through a loop to populate an array based on the input. Subsequently, these values get updated in 3 different gra ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

What are the drawbacks of implementing two-way binding between a parent component and a child component in a software system?

Lately, I have been focused on AngularJS development but recently I started exploring Vue.js and going through its guide. On one of the pages, I came across the following: By default, all props form a one-way-down binding between the child prope ...

Leveraging useEffect (or a comparable method) within a class component to create a loading screen

As a React newbie, I recently created a loading screen using useEffect in a functional component. Now, I'm trying to achieve the same using class components, but I'm facing some challenges. Here is the functional component that works perfectly: c ...

How can I dynamically change the orderBy parameter based on conditions in an Angular application?

I need to dynamically change the orderBy parameter in a table row based on the result of a method. Here is an example of my current tr setup - <tr class="pl" ng-repeat="thing in things | orderBy:'oldId':reverse" ng-class="{'row-error&apo ...

Application experiencing server error when updating MongoDB data

I have encountered an issue while trying to update/modify data that has already been uploaded in a reactjs project using mongoDB as the database. Whenever I attempt to update the data, an error is displayed. How can this problem be resolved? https://i.sta ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

How to eliminate arrows in ngx-bootstrap datepicker?

I recently started working with Angular and Bootstrap and I'm facing an issue. I am using a ngx bootstrap datepicker, but I would like to remove the standard arrows on the buttons of the datepicker calendar. Here is a screenshot of the problem: https ...

Identifying keystrokes and triggering audio in Vue.js

Utilizing vue.js, the code snippet provided enables sound playback upon each button click. I am curious about how one can detect a keyboard press event to play a sound when the DOM is ready rather than waiting for button clicks. For instance, triggering ...

Issues have arisen with Google Maps functionality following the API integration, resulting in a blank grey

I am experiencing an issue with Google Maps where it is displaying a grey box or sometimes showing nothing/white. I have tried various solutions found online but none of them have worked for me. Does anyone have a solution? I even attempted to change the ...

What could be causing my code to lag by 2 ticks instead of just 1?

Apologies for any spacing issues. Player = { move: function(cycle, opponent) { switch(cycle.current_direction) { case 'up': cycle.y -= cycle.height; break; case 'down': cycle.y += cycle.hei ...

Node/Express: The $ symbol is failing to recognize the input for PORT 8080

What steps should I follow to run my PORT on 8080? Is it necessary to install any dependencies? const app = require('express')(); const PORT = 8080; app.listen( PORT, () => console.log('It's now running on http://localhost:$ ...