Error: Unhandled promise rejection: [object Boolean]

I am encountering an issue while trying to secure a route in my Angular application. Despite what I believe to be the correct implementation, I am facing an error message when the negative scenario is triggered:

ERROR Error: Uncaught (in promise): [object Boolean]
. Interestingly, everything seems to function properly when I meet the requirements to access the route. Below is the relevant code:

Routing Module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';


import { RecipesComponent } from './recipes/recipes.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { RecipeDetailComponent } from './recipes/recipe-detail/recipe-detail.component';
import { RecipeStartComponent } from './recipes/recipe-start/recipe-start.component';
import { RecipeEditComponent } from './recipes/recipe-edit/recipe-edit.component';
import { AuthGuard } from './shared/guard.service';

const appRoutes: Routes = [
    {path: '', redirectTo: '/recipes', pathMatch: 'full' },
    {path: 'recipes', component: RecipesComponent, 
              children:[
        {path: '', component: RecipeStartComponent},
        {path: 'new', component:RecipeEditComponent},
        {path: ':id', component: RecipeDetailComponent, canActivate: [AuthGuard]},
        {path: ':id/edit', component:RecipeEditComponent}
    ]},
    {path: 'shopping-list', component: ShoppingListComponent}
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [RouterModule]
})

export class AppRoutingModule {

}

Auth Service


import { OnDestroy, Injectable } from "@angular/core";
import { RecipeService } from "../recipes/recipe.service";

@Injectable()

export class AuthService implements OnDestroy  {

constructor(private recipeService: RecipeService){
  console.log(this.loadedRecipe)
}

private loadedRecipe: boolean = false

setRecipe(){
this.loadedRecipe = true;
console.log(`setting the recipe to true`)
}

isAuthenticated() {
  const promise = new Promise(
    (resolve, reject) => {
      if(this.recipeService.getRecipes().length > 0){
        console.log(`resolving`)
        resolve(true)
      }else{  
        console.log(`rejecting`)
        reject(false)
      }
    }
  );
  return promise;
}

ngOnDestroy()
{
  console.log(this.loadedRecipe);
}

}

Guard Service

import {
    CanActivate,
    CanActivateChild,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    Router
  } from '@angular/router';

  import { Injectable } from '@angular/core';
  import {Observable} from 'rxjs'

  import { AuthService } from './auth.service';

  @Injectable({
    providedIn: 'root'  
})
  

  export class AuthGuard implements CanActivate, CanActivateChild {

    constructor(private authService: AuthService, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
                      return this.authService.isAuthenticated() 
                    .then(
                  (authenticated: boolean) => {
                      if (authenticated) {
                         console.log(`got here1`)
                            return true;
                        } else {
                          console.log(`got here2`)
                            this.router.navigate(['/recipes']);
                        }
                    }
                )
            }

    canActivateChild(route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
            return this.canActivate(route, state);
        }
  }

If anyone can shed light on what might be causing this issue, I would greatly appreciate it!

Answer №1

The potential issue lies within the else statement in the gothere2 case. It seems that the authentication is not being properly handled as expected. In this scenario, a Boolean value is supposed to be returned but nothing is currently being returned. On the other hand, the authentication case is returning a value. To resolve this issue, you should make sure to return a value in both the if and else statements as shown below:

              (authenticated: boolean) => {
                  if (authenticated) {
                     console.log(`got here1`)
                        return true;
                    } else {
                      console.log(`got here2`)
                        this.router.navigate(['/recipes']);
                            return false;

          }

Answer №2

After testing it on my end, I encountered the same error and found a solution. https://i.sstatic.net/NBHLE.png

The screenshot clearly demonstrates that I have restricted user access to the server route. Here is my initial Auth service with the isAuthenticated() method: https://i.sstatic.net/0oRjA.png

To resolve this issue, we must implement error handling as illustrated below: https://i.sstatic.net/YMJPY.png

Thanks to these adjustments, the error no longer persists. https://i.sstatic.net/qNOLp.png

Answer №3

Encountered a similar issue, albeit in a different context from the original poster.

In my case, I encountered an error when rejecting a promise within an await statement. It seemed that the error was not being caught properly after rejection, leading to the message "Error: Uncaught (in promise): [object Boolean]".

I was able to fix this error by wrapping the await statement in a try-catch block.

Sharing my code snippet below for reference:

DataService.ts

serviceCall(): Promise<SomeEntity | HttpErrorResponse> {
    return new Promise((resolve, reject) => {
        myService.doSomeWork()
        .then(data => {
            resolve(data);
        })
        .catch(error => {
            reject(error)
        })
    })
}

Component.ts

try {
    await DataService.serviceCall();
} catch (error) {
    // Catching errors from rejected promises here
    console.log(error)
}

Answer №4

If you encounter an error, try accessing it in incognito mode to troubleshoot the issue.

Answer №5

If you are utilizing version 7 or higher, consider replacing the following line:

this.router.navigate(['/recipes']);

with:

return this.router.parseUrl('/recipes');

You can also remove the additional code specifying:

: Observable<boolean> | Promise<boolean> | boolean

as typescript will be able to deduce it automatically.

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

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me. ...

Twitter typeahead with a dynamic array of strings

Currently, I am making an ajax call to retrieve a list of objects. Once this array of objects is filled, a separate string[] is created with the names of these objects. My goal is to pass this data to Twitter Typeahead using a Bloodhound source. However, ...

Ways to determine if your code is written in ES6

After completing a lot of Javascript coding, I just learned about the existence of various JS 'versions' such as ES5 and ES6. My project is now up on Github, and someone advised me to convert my ES6 code to ES5 using Babel. The problem is, I&ap ...

Modify requests to targeted URLs manually in Browsersync

In my current setup, I am utilizing BrowserSync in a unique way. I have my web server (Apache in a Docker container) proxied, but I am also serving hot module replacement (HMR) from a Webpack dev server. In my local development environment, the configurat ...

What is the best approach to create an isLoggedIn function using Angular Firebase?

Implementing an isLoggedIn method using Firebase in my Angular 6 app has been a challenge. The firebase user object behaves like a "subscription" object, making it difficult to use as a regular method. This is my current implementation: export class Angu ...

Difficulties with angular ui-router authentication problems

When setting notify to true, the login.html does not render - it shows up as a blank page. However, if set to false, I receive multiple errors in the console: RangeError: Maximum call stack size exceeded at $.resolve (angular-ui-router.min.js:1) a ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. https://i.sstatic.net/8tdfV.png The shifting dot in each imag ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Steps to configure caching settings to ensure no caching for the entire site during specific hours, and constant no-cache policy for a particular page

Managing cache for my website has become quite the challenge. Some pages need to be cached during certain hours to improve navigation speed, while others must not be cached during crucial data update times. And to add to the complexity, there are pages tha ...

Is it possible for Angular models to have relationships with one another? Can one model make references to

I have a complex navigation structure set up like this to create the top nav: [ {id: 1, label: 'Home', icon: 'fa-home', subitems: []}, {id: 2, label: 'Sitemap', icon: 'fa-sitemap', subitems: []}, ...

Is it possible to use reactjs and react-router to showcase either a component or {this.props.children}?

Here's the scene: I have multiple components where certain words can be clicked to link to a reference page/component. If the highlighted words are not clicked, the component is displayed as is (and there are many of them with this feature and a menu ...

Take users to another page upon form submission

I'm working on a React form using Typescript and Material-UI. Here's an example: import React, { useState } from "react"; import TextField from "@material-ui/core/TextField"; import { createStyles, makeStyles, Theme } from &qu ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

Moving the panel to follow the mouse cursor in Firefox Add-on SDK

Is there a way to show a panel on the screen at the exact position of the mouse? I'm finding it difficult to understand how to change the position of the panel in Firefox SDK, as the documentation lacks detailed information. ...

What is the best way to operate both a Django and React server concurrently?

Is it feasible to run both Django and React.js servers simultaneously? Currently, I have to individually start the Backend server using python manage.py run server and then switch to Frontend to run npm start. I am working on a Fullstack project with sepa ...

Can an Angular 2 module export an interface?

While attempting to export an interface in a NgModule-declaration, I encountered an error message in my editor (Visual Studio Code) stating: [ts] 'MyInterface' only refers to a type, but is being used as a value here. Below is the code snippet c ...

Query parameter is not defined

Can anyone assist me with extracting the ean from the following URL: This NodeJS server processes the request in the following manner: const http = require('http') const port = 3000 const requestHandler = async (request, response) => { ...

Transfer data to the local context of JavaScript functions

My usual approach involves using a structure similar to this: var $this, url, callback; //private variables loadCallback = function($that, url, callback) { return function(responseText, textStatus, req) { ... }; })($this, url, callback) H ...

Setting the $dirty flag to true when a value is entered in the text box, but not the other way around

When I enter a value in the text box, myForm.$dirty gets set to true. However, the flag does not revert back to false when I delete all values from the text box. Why is this happening and how can I fix it? <input name="input" ng-model="myModel.text"& ...