嵌套在Angular方法

时间:2017-11-29 15:26:49

标签: angular typescript

我有一个简单的列表,我想让我的代码工作而不必更新三次admin2对象(我只想使用admin2一次,我需要{{ 1}}等于(property)admin2

换句话说,我需要使用不同的分页projectPagination更新此admin2:IPaginationResponse,consultantPagination:IPaginationResponse,newsletterPagination:IPaginationResponse

Admin2Component.admin2: IAdmin2

后来:

private updateList(
    projectPagination: IPaginationResponse <IProject>,
    consultantPagination: IPaginationResponse <IConsultant>,
    newsletterPagination: IPaginationResponse <INewsletter>
) {
    this.admin2 = projectPagination.data;
    this.pagination.total = projectPagination.meta.pagination.total;
    this.pagination.page = projectPagination.meta.pagination.current_page;

    this.admin2 = consultantPagination.data;
    this.pagination.total = consultantPagination.meta.pagination.total;
    this.pagination.page = consultantPagination.meta.pagination.current_page;

    this.admin2 = newsletterPagination.data;
    this.pagination.total = newsletterPagination.meta.pagination.total;
    this.pagination.page = newsletterPagination.meta.pagination.current_page;
}

1 个答案:

答案 0 :(得分:1)

根据我的理解,您有3组不同的分页值,您需要在组件中引用所有3。但是你要做的是将一组类属性一个接一个地重新分配给所有3个值。这不会给你想要的结果,因为你的类属性总是等于最后一个赋值。

创建另外两组类属性,所以你应该从这样的东西:

class MyClass {
    admin2: any;
    pagination: any;

    // ...
}

对于这样的事情(给他们更好的名字,我只是遵循你的命名惯例):

class MyClass {
    admin: IProject;
    pagination: IPaginationResponse<IProject>;

    admin2: IConsultant;
    pagination2: IPaginationResponse<IConsultant>;

    admin3: INewsletter;
    pagination3: IPaginationResponse<INewsletter>;

    // ...
}

因此,它为您提供了3组不同的类属性,每个属性代表组件的不同分页对象。

现在更改您的updateList函数以分配所有3组属性,而不是重新分配一组属性3次:

private updateList(
    projectPagination: IPaginationResponse <IProject>,
    consultantPagination: IPaginationResponse <IConsultant>,
    newsletterPagination: IPaginationResponse <INewsletter>
) {
    this.admin = projectPagination.data;
    this.pagination.total = projectPagination.meta.pagination.total;
    this.pagination.page = projectPagination.meta.pagination.current_page;

    this.admin2 = consultantPagination.data;
    this.pagination2.total = consultantPagination.meta.pagination.total;
    this.pagination2.page = consultantPagination.meta.pagination.current_page;

    this.admin3 = newsletterPagination.data;
    this.pagination3.total = newsletterPagination.meta.pagination.total;
    this.pagination3.page = newsletterPagination.meta.pagination.current_page;
}

确保首先实例化您的类属性,或者它们都是undefined,因此执行this.pagination.foo之类的操作会为您提供“无法访问foo未定义”错误。< / p>