英文:
Pass Specific Parameter to Method Angular 15
问题
我有一个使用生成的管道api-service的Angular 15应用程序。在服务中,我有一个用于获取项目列表的方法,但我不确定如何以任意顺序传递参数。
在调用这个方法时,只要我按正确的顺序使用正确数量的参数,我就能发送参数,但当我尝试传递特定内容时,会出现错误。
这是你的代码块,其中出现了问题:
this.getList(undefined, 1); #返回列表
this.getList(size: 1); #抛出错误
我记得以前可以这样做,但我无法记住或找到这种语法。
英文:
I have an Angular 15 app that uses a pipeline generated api-service. In the service I have a method for getting a list of items, but I am not sure how to pass parameters in any order.
public getList(page?: number | undefined, size?: number, type?: string, completed: boolean = false) {
....
}
When calling this method, I am able to send params as long as I use the correct number of params in the correct order, but I get an error when I try to pass in something specific
this.getList(undefined, 1) #returns list
this.getList(size: 1); #throws error
I remember being able to do this before, but I can't remember nor find the syntax for this
答案1
得分: 1
JavaScript 和 TypeScript 不支持 命名参数。
最接近的方法是定义一个接口,然后传入与该接口对应的对象:
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 });
英文:
JavaScript and TypeScript do not support named parameters.
The closest you can get is defining an interface, and passing in an object that corresponds to that interface:
interface Params {
page?: number;
size?: number;
type?: string;
completed: boolean;
}
function getList(params: Params = { completed: false }) {
// ...
}
getList({ size: 1, completed: false });
If you want to avoid having to repeat parameters for which you have a default value, you can define an object with default parameters, and use a 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 });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论