TS2345:无法将类型“ RolesGuard”的参数分配给类型“ CanActivate”的参数

时间:2020-03-02 07:31:20

标签: angular typescript routing

错误TS2345:“ RolesGuard”类型的参数无法分配给 “ CanActivate”类型的参数。属性“ canActivate”的类型为 不相容。 类型'(req:any,context:ExecutionContext)=>任何'都不能分配给类型'(context:ExecutionContext)=>布尔值| 承诺|可观察的”。

app.useGlobalGuards(new RolesGuard(new Reflector()));

这是我的代码的样子。

app.useGlobalGuards(new RolesGuard(new Reflector()));
import { Guard, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs/Observable';
import { merge, reduce } from 'rxjs/operators';

import { from } from 'rxjs/observable/from'
import { Reflector } from '@nestjs/core';
import { getManager } from "typeorm";
import { MODULES, FEATURES } from '../constant';

@Guard()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) { }

  canActivate(req, context: ExecutionContext): Promise<boolean> {
    const { parent, handler } = context;
    const permissions = this.reflector.get<string[]>('Permission', handler);
    if (!permissions) {
      return new Promise((res, rej) => { res(false) });
    }
    .
    .
    .
    .
    //if there are more than two set of permissions
    if (permissions.length > 3) {
      let perms = Array.from(permissions);
      perms.splice(2, 1);
      let whereClause = perms.reduce((acc, val, index) => {
        let paramNo = index + 2;
        if (index % 2 === 0) {
          return `${acc}(module=$${paramNo}`;
        } else {
          return `${acc} AND feature=$${paramNo}) OR `
        }
      }, "");
      .
      .
      .
    }

    return entityManager.query(sql, params).then(res => {
      let perms = <Array<any>>res;
      let type = permissions[2].toLowerCase();
      if (type === 'view') {
        return perms.reduce((acc, val) => { return (val['canview'] || val['canedit']) || acc }, false);
      } else if (type === 'edit') {
        return perms.reduce((acc, val) => { return val['canedit'] || acc }, false);
      } else {
        return false;
      }
    });
  }
}

1 个答案:

答案 0 :(得分:0)

您的界面签名错误。由于某些原因,您添加了一个冗余的req参数。

在NestJS文档中,这是守卫应该看起来像的正式示例:


import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return true;
  }
}

请注意,canActivate仅具有一个参数-context: ExecutionContext。从错误消息中也很明显。

因此,您应该可以通过删除req来解决问题。