简体   繁体   English

错误:未捕获(承诺):[object Boolean]

[英]Error: Uncaught (in promise): [object Boolean]

I am trying to protect one of my routes in this Angular app I have made.我正在尝试在我制作的这个 Angular 应用程序中保护我的一条路线。 I think I have implemented it correctly however, am running into this error when the negative scenario is invoked: ERROR Error: Uncaught (in promise): [object Boolean] .我想我已经正确地实现了它,但是当调用负面场景时遇到了这个错误: ERROR Error: Uncaught (in promise): [object Boolean] What I also can't understand is that it seems to work when I meet the conditions to allow the route?!我也无法理解的是,当我满足允许路线的条件时,它似乎起作用了?! Code below:下面的代码:

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.loadedReceipe)
}


private loadedReceipe: boolean = false

setRecipe(){
this.loadedReceipe = 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.loadedReceipe);
}

}

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);
}




  }

Does anyone know what is going on here?有谁知道这里发生了什么? Any help would be much appreciated!任何帮助将非常感激!

I would expect the issue to be in the else in the gothere2 case.我希望问题出在 gothere2 案例中的 else 中。 It is not authenticating and is promised to return a Boolean.它没有进行身份验证,并承诺返回一个布尔值。 However you are not returning anything.但是,您没有返回任何东西。 Where in the authentication case you are.您在身份验证案例中的位置。 How I would fix:我将如何解决:

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

          }

Faced the exact same error but for a different scenario than the OP's.面临完全相同的错误,但与 OP 的情况不同。

I was rejecting a promise for an await statement and looked like error couldn't find a place to get caught after rejection and threw "Error: Uncaught (in promise): [object Boolean]".我拒绝了等待语句的承诺,并且看起来错误在拒绝后找不到被捕获的地方并抛出“错误:未捕获(在承诺中):[object Boolean]”。

Placing my await statement under try catch block fixed the error.将我的 await 语句放在 try catch 块下修复了错误。

Adding my code below in case someone encounters same issue:如果有人遇到同样的问题,请在下面添加我的代码:

DataService.ts数据服务.ts

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

Component.ts组件.ts

try {
    await DataService.serviceCall();
} catch (error) {
    // error from the rejected promise should get caught here
    console.log(error)
}

I have tried it out from my end was getting the same error and this is how i fixed it.我已经尝试过了,我得到了同样的错误,这就是我修复它的方法。 在此处输入图像描述

As you can see in the screen shot I am not allowing the user to access the server route.正如您在屏幕截图中看到的那样,我不允许用户访问服务器路由。 My Initial Auth service with isAuthenticated() method is as following我使用 isAuthenticated() 方法的初始身份验证服务如下在此处输入图像描述

In order to prevent this error we need to catch it as shown below.为了防止这个错误,我们需要捕获它,如下所示。 在此处输入图像描述

Now i am not getting any error.现在我没有收到任何错误。 在此处输入图像描述

有时由于 catch 尝试以隐身模式打开它而出现错误

Assuming you are using the version >=7.假设您使用的版本 >=7。 Try to replace尝试更换

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

with

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

You may also get rid of你也可以摆脱

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

as typescript will be able to infer it.因为打字稿将能够推断出它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:错误错误:未捕获(承诺):[对象布尔] - Error : ERROR Error: Uncaught (in promise): [object Boolean] 错误:未捕获(承诺):[object Object] - Error: Uncaught (in promise): [object Object] 吞下的消息:错误:未捕获(承诺):[对象未定义] - Swallowed message : Error: Uncaught (in promise): [object Undefined] 未被捕获(承诺):错误:找不到“ [对象对象]”的NgModule元数据 - Uncaught (in promise): Error: No NgModule metadata found for '[object Object]' 未捕获(承诺):服务器错误 - Uncaught (in promise): Server error Promise 中的 ComponentDidMount 未捕获错误 - ComponentDidMount Uncaught Error in Promise 未捕获(承诺)错误 - Uncaught (in promise) Error ng-recaptcha ERR:错误:“未捕获(承诺):[对象空]” - ng-recaptcha ERR: Error: "Uncaught (in promise): [object Null]" Wasm: Uncaught (in promise) TypeError: Import #0 module=&quot;env&quot; error: module is not an object or function Promise.then (async) (anonymous) @ (index):9 - Wasm: Uncaught (in promise) TypeError: Import #0 module="env" error: module is not an object or function Promise.then (async) (anonymous) @ (index):9 使用Mocha测试Promise时出现未捕获(In Promise)错误 - Uncaught (in promise) error when testing promise with Mocha
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM