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

时间:2019-07-19 20:37:08

标签: javascript angular typescript angular-router

我正在尝试保护自己制作的Angular应用中的一条路线。我认为我已经正确实现了,但是在调用否定方案ERROR Error: Uncaught (in promise): [object Boolean]时遇到此错误。我也无法理解的是,当我满足允许路线的条件时,它似乎可以工作?下面的代码:

路由模块

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 {

}

身份验证服务


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

}

警卫服务

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




  }

有人知道这里发生了什么吗?任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:1)

我希望问题出现在gothere2案件的其他案件中。它不进行身份验证,并承诺返回布尔值。但是,您什么也没退。在身份验证的情况下,您在哪里。我将如何解决:

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

          }

答案 1 :(得分:0)

解决了与OP完全相同的错误,但针对的场景不同。

我拒绝了对await语句的承诺,并且看起来错误在拒绝后找不到地方,并抛出了“错误:未捕获(承诺):[object Boolean]”。

将我的await语句置于try catch块下即可解决该错误。

如果有人遇到相同的问题,请在下面添加我的代码:

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) {
    // error from the rejected promise should get caught here
    console.log(error)
}

答案 2 :(得分:0)

我已经尝试过,结果出现了同样的错误,这就是我修复它的方法。 enter image description here

正如您在屏幕截图中看到的,我不允许用户访问服务器路由。 我使用 isAuthenticated() 方法的初始身份验证服务如下 enter image description here

为了防止这个错误,我们需要捕获它,如下所示。 enter image description here

现在我没有收到任何错误。 enter image description here

答案 3 :(得分:-1)

假设您使用的版本> = 7。尝试更换

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

使用

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

您也可以摆脱

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

因为打字稿可以推断出来。