Error: Promise was not caught - The request to the URL returned an unauthorized status code of 401

https://i.sstatic.net/9lewp.pngImplementing authGuard for my Routers has been a challenge. Whenever I try to handle error codes, it ends up breaking the entire application. I'm currently at a loss on how to resolve this issue and would greatly appreciate any assistance.

Below is the code snippet for My AuthGuard:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    return this._auth.validate()
      .map((isValidated) => {
        if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) {
          return true;
        }
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
        return false;
      });
  }

And here is part of My Auth Service:

@Injectable()
export class AuthService {

  loginStatus;

  constructor(private http: Http, private _apiEndPoint: ApiEndPoint, private router: Router) { }

  validate() {

    return this.http.get(this._apiEndPoint.validate)
      .map(
      (response: Response) => {

        const result = response.json();

        // Check authentication status from response
        if (result.authenticated) {
          return true;
        } else {
          return false;
        }
      })
    .catch(error => Observable.throw(error));
  }

}

I am encountering an error: "Uncaught (in promise): Response with status: 401 Unauthorised for URL."

https://i.sstatic.net/9lewp.png

Whenever this error occurs, my page just goes completely blank.

Answer №1

My solution involved changing the code to return an observable of false.

return this._auth.validate()
      .map((isValidated) => {
        if (isValidated && localStorage.getItem('authToken') && this.checkCookie()) {
          return true;
        }
      }).catch(() => {
        this.router.navigate(['/login']);
        return Observable.of(false);
      });

Answer №2

In order to handle errors, you must implement a try-catch block that returns an observable.

validate() {

return this.http.get(this._apiEndPoint.validate)
  .map(
  (response: Response) => {

    const result = response.json();

    // Check authentication status from response
    return result.authenticated;
  })
  .catch(error => Observable.throw(error)); // If you want to throw nothing, then return Observable.empty()
}

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

The specified component does not contain a property named n according to the modal error

I am new to Angular and currently working on showing a modal when clicking a marker. Despite successful compilation, I am still encountering errors at times. Could it be due to jQuery setup issues? This code is located within the HomeComponent component. ...

Can a custom structural directive be utilized under certain circumstances within Angular?

Presently, I am working with a unique custom structural directive that looks like this: <div *someDirective>. This specific directive displays a div only when certain conditions are met. However, I am faced with the challenge of implementing condit ...

Tip Sheet: Combining Elements from an Array of Objects into a Single Array

When I invoke the function getAllUsers() { return this.http.get(this.url); } using: this.UserService.getAllUsers().subscribe(res => { console.log(res); }) The result is: [{id:1, name:'anna'}, {id:2, name:'john'}, {id:3, name ...

Interactive Ionic menu available on a designated page for enhanced user engagement

English is not my first language, so please bear with me. Here's the situation: I have a map section (using leaflet) on one page of my app, along with a menu for displaying data to the user. Currently, the menus are located in my app.component.html b ...

Removing validators in Angular forms after submitting the form and resetting it

I am currently working on an Angular app that includes a form. Whenever I click the submit button, the reset() function gets triggered on the form. However, after the reset() function is called, all inputs are marked as having errors. I have tried using fu ...

The Angular2 project using ag-grid-enterprise is currently experiencing difficulties with implementing the License Key

I have a valid license for the ag-grid-enterprise version, but I'm struggling with how to integrate it into my Angular2 project. I've attempted placing the license in the main.ts file using LicenseManager and specifying the enterprise version in ...

Transmit information from an Angular application to a Spring Boot server using a POST request

Attempting to send JSON data from a frontend Angular project to a Spring Boot backend for the first time. Limited experience with both technologies and unsure if the HTTP POST method in Angular is incorrect, or if the backend isn't receiving the expec ...

Exporting Arrays in Ionic Angular with Typescript is an essential feature

When trying to access an exported component in Typescript, there may be issues with importing the module correctly into another component. An error message is displayed when calling the AddToArray method: Cannot read property 'push' of undefi ...

Updating the state across various components proves to be a challenge when relying on both the context API and higher order components

I have been working on updating the application state using the context API instead of using Redux, as I do not require all of its features and want to avoid prop drilling. With TypeScript, I created a global context and a higher-order component (HOC) wrap ...

Establish a global variable within a TypeScript file

I am currently facing an issue where I need to add an event to the browser inside the CheckSocialMedia function. However, it keeps saying that it could not find the name. So, my question is how do I make the 'browser' variable global in the .ts ...

Angular CLI produced the Git command

After starting a project with the Angular CLI, I know it should create a git for me. I typed the following commands in my project directory: git add . git commit -m "some message" Now I want to push. Where do I push this to? Or where is the GitHub r ...

Combining two arrays in typescript using the map method

I have an array of heart rate, height, and weight values. { "heart_rate": 27, "height": 82, "weight": 78 } There is also a second array containing information about each value, such as ID, label, and description. ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Encountering an issue with Auth0 and Angular2: "The supplied parameters do not match any signature of call target."

I'm currently in the process of integrating Auth0 with my Angular2 application using angular2-cli. I've added a new service called auth, but when I try running npm start, I encounter an error stating: src/app/auth.service.ts (21,5): Supplied para ...

What is the best way to determine if an Observable value is filled in Angular?

One of the challenges I am facing in my app development is the need to centrally load data using a single HTTP request and pass it on to multiple components. To achieve this, I have utilized the BehaviourSubject class to store the loaded data in an observa ...

Discover the steps to designing an Angular 2 library project

Could someone assist me in developing a basic Angular 2 library project with just one Angular 2 component? Once this is done, I would like to utilize this library component in another project that was created using the Angular CLI command. The main goal i ...

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

Ways to dynamically emphasize text within ngFor loop

Within my ngFor loop, I have a set of rows. <div *ngFor="let block of data;"> <div class="class-row"> <div class="left">A Label:</div> <div class="right">{{block.key1}}</div> </div> <div class="clas ...

Exploring StickIt: Binding the length property from a backbone.Collection

Exploring the use of Backbone, Marionette (1.8.3), StickIt, and TypeScript to effectively bind the length of a Backbone collection in real-time as items are added or removed. As someone new to StickIt, here's my current attempt: export class SomeVie ...

AngularJS Kendo Date Picker: A Simplified Way to Select

Having trouble with formatting dates in my local timezone, the date picker is displaying it incorrectly. Here's an example of the code: input id="logdate" kendo-date-picker="logdate" k-options="logdateOptions" data-ng-model="logFilter.date" k-ng-mode ...