![](/img/trans.png)
[英]TS2345: Argument of type 'Event' is not assignable to parameter of type 'HtmlInputEvent'
[英]TS2345: Argument of type 'RolesGuard' is not assignable to parameter of type 'CanActivate'
错误 TS2345:“RolesGuard”类型的参数不可分配给“CanActivate”类型的参数。 属性“canActivate”的类型不兼容。 类型 '(req: any, context: ExecutionContext) => any' 不可分配给类型 '(context: ExecutionContext) => boolean | 承诺 | 可观察'。
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;
}
});
}
}
你的接口签名是错误的。 出于某种原因,您添加了一个冗余的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
来解决你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.