【问题标题】:Pass Specific Parameter to Method Angular 15将特定参数传递给方法 Angular 15
【发布时间】:2023-02-08 16:03:07
【问题描述】:
我有一个使用管道生成的 api 服务的 Angular 15 应用程序。在服务中,我有一个获取项目列表的方法,但我不确定如何以任何顺序传递参数。
public getList(page?: number | undefined, size?: number, type?: string, completed: boolean = false) {
....
}
调用此方法时,只要我以正确的顺序使用正确数量的参数,我就可以发送参数,但是当我尝试传递特定内容时出现错误
this.getList(undefined, 1) #returns list
this.getList(size: 1); #throws error
我记得以前能做到这一点,但我不记得也找不到它的语法
【问题讨论】:
标签:
angular
typescript
angular15
【解决方案1】:
JavaScript 和 TypeScript 不支持 named parameters。
您可以获得的最接近的是定义一个接口,并传入与该接口对应的对象:
interface Params {
page?: number;
size?: number;
type?: string;
completed: boolean;
}
function getList(params: Params = { completed: false }) {
// ...
}
getList({ size: 1, completed: false });
如果您想避免重复具有默认值的参数,您可以定义一个具有默认参数的对象,并使用 Partial<Params>:
interface Params {
page?: number;
size?: number;
type?: string;
completed: boolean;
}
const defaultParams: Params = {
completed: false
};
function getList(partialParams: Partial<Params>) {
const params: Params = Object.assign({}, defaultParams, partialParams);
// ...
}
getList({ size: 1 });