Issue with handling http errors and navigating routes in Angular 2

Whenever I check a user's token authentication and encounter a 401 error, I aim to redirect them to the login page. The issue arises when attempting to navigate to the login page within the error catch block.

constructor(private http: Http , private router : Router)


authUser(){
        return this.http.get(this.baseEndPoint+'/auth/user',Helpers.requestAuthOptions())
            .map((response) => response.json())
            .catch(this.handleErrors.bind(this));
    }

 public handleErrors = (error) => {
        this.router.navigate(['/login']);
        console.log('Hello!');//Hello appears in my console
        return Observable.throw(error);
    };

Answer №1

Simply add the RxJS catch Extension to your project using the following code:

import 'rxjs/add/operator/catch';

Learn how to properly handle exceptions from http requests here.

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

Angular2 encountering a lack of service provider issue

After finding the code snippet from a question on Stack Overflow titled Angular2 access global service without including it in every constructor, I have made some modifications to it: @Injectable() export class ApiService { constructor(public http: Http ...

Ensuring File Size and Format Compliance in Angular's HTML and TypeScript

I'm currently tackling a file upload feature on an ASP.net webpage using Angular. I have a question: How can I verify if the uploaded file is either a PDF or JPG and does not exceed 2MB in size? If these conditions are not met, I would like to displa ...

Tips for passing a Typescript variable in a jquery callback function

Within an Angular 6 component, I am utilizing a jQuery callback function. This component contains a TypeScript variable, and when a click event occurs on the webpage, the callback function is triggered. However, I am struggling to figure out how to pass th ...

Tips for detecting HTML updates using Python requests

My goal is to monitor a page for updates while maintaining the same session and cookies, without sending a completely new request. How can I determine if there are HTML updates within my current request? The page will redirect but keep the same URL. This ...

Best approach for managing Angular dependencies: Is it acceptable to link to a TypeScript file other than its corresponding component.ts in a component.html file?

My friend and I recently had a disagreement about a file in our project called experiment-row.component.html. The code in question looked like this: *ngIf="experimentsPageService.isRegularStatusIconVisible(experiment)" I argued that it is not go ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

IntelliJ IDEA does not support the recognition of HTML tags and directives

I seem to have lost the ability to switch between my HTML and TS files in Intellij IDEA; the tags, directives, and autocompletion in HTML are no longer working. Additionally, I'm receiving some warnings: https://i.stack.imgur.com/QjmNk.png Is there ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

Issue: fs.js:47 } = primordials; ^ ReferenceError: primordials is not defined - Please handle this error

I encountered an issue where my node version is 12.11.1, however when I try running the command npm run server, it returns an error message as displayed below: fs.js:47 } = primordials; ^ ReferenceError: primordials is not defined at fs.js:47:5 ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Extracting PNG file from response (bypassing standard JSON extraction)

Despite my efforts to find a solution, I am still unable to resolve this specific issue: I have implemented an Angular request (localhost:4200) to an API on Spring (localhost:8080). The HttpService successfully handles the requests, except when it comes to ...

Optimizing font loading with angular CLI

EDIT: AFAIK This is a unique question and not related to Webpack disable hashing of image name on output because: The webpack.config file is no longer editable in the latest versions of Angular CLI. I actually want to keep the hash on the fon ...

Utilize the routerLink within a string value on a HashMap instance

I am currently storing translated parameters in a HashMap object on my component. However, I am facing an issue where certain attributes such as [routerLink] are not functioning properly or not being interpreted by Angular (v5). Here is the code snippet f ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

Having trouble retrieving the date value from a datepicker in Angular ngForm

I am struggling to fetch a value from the mat-datepicker in my Angular project. Whenever I try, it returns as undefined. I have implemented ngForm and ngModel, but I seem to have made a mistake somewhere. <form #f="ngForm" (ngSubmit)="registerClient(f. ...

Setting up an auto-complete dropdown with PrimeNG and Angular

Struggling with the auto-complete feature, where the dropdown loads initially but fails to filter values as I type. Here's a snippet from service.ts: getUserLocations(UserID: string, allList:string ) { return this._http.get(environment.BASE ...

What exactly is the concept behind the Strategy OnPush?

I am a beginner in the world of Angular2 with TypeScript. As I delve into my project, one concept that continues to elude me is the purpose of OnPush: changeDetection : ChangeDetectionStrategy.OnPush Despite my dedicated efforts in researching this top ...

Angular2 with Electron is a stellar demonstration of a successful integration

I'm interested in exploring Electron with Angular2 and I'm on the lookout for a reliable example on GitHub that combines these technologies. Ideally, I would like to find a repository that I can easily download as a zip file, run npm install, npm ...

AG Grid is displaying improperly within Angular

I am facing an issue with using ag-grid in my project. The output is not as expected and I am unsure of what the problem might be. Here is a snippet of my HTML code: <p>user-access works!</p> <ag-grid-angular style="width: 500px; height: 50 ...