我需要在list中找到对象。
这是我的列表:
export interface Controllermodel {
controllerDisplayName: string;
controllerFarsiName: string;
roleId: number;
controllerId: string;
actionsVM: Actionmodel[];
}
export interface Actionmodel {
displayName: string;
actionEnglishName: string;
actionId: number;
}
现在我需要在列表中查找对象,但是当我使用此代码时:
export class ValidatePermissionDirective implements OnInit {
show: boolean;
constructor(private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef
, private dynamic: DynamicPermissionService) { }
// tslint:disable-next-line:no-input-rename
@Input('appValidatePermission') AccessName:string;
ngOnInit() {
this.ValidatePemission();
if (this.show) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
}
}
ValidatePemission()
{
console.log(this.AccessName)
const find = this.dynamic.dynamicModel.find(x =>
x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
console.log(find)
if (find) {
console.log(false);
this.show = false;
} else {
console.log(true);
this.show = true;
}
}
}
但是当我使用此代码时,它向我显示此错误:
类型'Actionmodel'不能分配给类型'布尔'。
出什么问题了?我该如何解决这个问题?
答案 0 :(得分:1)
添加!!
以确保您的find
结果为布尔值:
const find = this.dynamic.dynamicModel.find(x =>
!!x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
find
使用一个参数:一个接受数组元素并返回boolean
的函数。返回的对象将是找到的实例或undefined
。
const find = this.dynamic.dynamicModel.find(
x => x.actionsVM.find(
z => z.actionEnglishName === this.AccessName));
在内部find
调用中,您有正确的答案:z.actionEnglishName === this.AccessName
返回一个boolean
。
在外部find
调用中,您将返回内部find
的结果,该结果将是Actionmodel实例或值undefined
。这些值可以强制为true
和false
,但是Typescript希望将其明确。通过以!!
开头,您可以确保“真实”值(如实例)将返回值true
,而“虚假”值(如undefined
)将返回值false
,符合Typescript对find
方法的定义。