使用canActivate或canChildActivate会引发错误吗?

时间:2018-08-23 15:57:52

标签: angular typescript

在子路由中使用canActivateChildcanActivate会引发错误。这个东西之前工作得很好,但是这次似乎有问题。它引发错误:

ERROR in src/app/app-routing.module.ts(8,7): error TS2322: Type '({ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Log...' is not assignable to type 'Route[]'.
  Type '{ path: string; redirectTo: string; pathMatch: string; } | { path: string; component: typeof Logi...' is not assignable to type 'Route'.
    Type '{ path: string; component: typeof MainContentComponent; canActivateChild: typeof PlayVidAuthGuard...' is not assignable to type 'Route'.
      Types of property 'canActivateChild' are incompatible.
        Type 'typeof PlayVidAuthGuardService' is not assignable to type 'any[]'.
          Property 'includes' is missing in type 'typeof PlayVidAuthGuardService'.

这是我的路由模块:

const appRoutes: Routes = [
  { path: "", redirectTo: "login", pathMatch: "full" },
  { path: "login", component: LoginComponent },
  {
    path: "home",
    component: MainContentComponent,
    canActivateChild: PlayVidAuthGuardService,
    children: [
      {
        path: "",
        component: PlayVideoComponent
      }
    ]
  }
];

现在,当我删除canActivateChild属性/字段时,错误消失了。

export class PlayVidAuthGuardService implements CanActivate {
  constructor() {}
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return true;
  }
}

即使我将canActivate放在子路由中,也遇到相同的错误。 我怎样才能解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:1)

您实现了CanActivate接口,但您分配给了canActivateChild。对于canActivateChild,您需要实现CanActivateChild接口。

此属性也必须使用数组初始化。

...
canActivateChild: [ PlayVidAuthGuardService ]
...

此错误

  

类型'typeof中缺少属性'includes'   PlayVidAuthGuardService”。

表示Angular试图在includes上找到名称为canActivateChild的函数,但由于您分配了 非数组 而找不到

答案 1 :(得分:0)

这些防护字段需要一个数组,因此请使用一个元素将防护包裹在数组中:

// Change this... 
// canActivate: YourGuard, 

//... to this:
//           v         v
canActivate: [YourGuard],