【问题标题】:angular 2 service extention: change datatype in functionangular 2 服务扩展:更改函数中的数据类型
【发布时间】:2021-07-08 01:00:13
【问题描述】:

在我的项目中,我创建了 list.service.ts,它包含列表的任何功能,从从 API 加载 json 对象列表、将 API 结果映射到行、分页等等......

对于每个列表类型(用户、项目...),我用额外的数据、属性和功能扩展了这项服务。

export class UsersListService extends ListsService {...}

在扩展服务的所有变化中,API 结果格式(数据类型)发生变化。

我的 MapData 函数(通用)如下所示:

MapData(resultsData: any[], columns: NgListColumns[]): NgListDataRow[] {...}

用户列表服务中的函数如下所示:

MapData(resultsData: UserApiData[], columns: NgListColumns[]): NgListDataRow[] {...}

所以唯一的变化是 resultsData 的数据类型。

相同的更改将应用​​于其他一些功能。

我的问题:有什么方法可以将此数据类型作为主服务中的参数并自动应用于扩展服务?

现在我必须在服务扩展中重写所有这些函数,但这迫使我跟踪主服务中这些函数的任何更改,并修复所有扩展服务中这些函数的所有副本。

【问题讨论】:

    标签: angular angular-services


    【解决方案1】:

    我认为您正在寻找 TypeScript 中泛型的概念。

    在你的一般ListsService中尝试这样的事情

    // T will be a type that the consuming "component" will specify when using this method
    MapData<T>(resultsData: T[], columns: NgListColumns[]): NgListDataRow[] { ... }
    

    那么要使用你的方法,你会这样做:

    // the <...> here populates the type of the generic when we are consuming it
    this.userListService.MapData<UserApiData>(x, y, z);
    

    这样(我假设)您不必为了类型正确而复制方法。

    了解更多关于泛型here

    【讨论】:

    • 昨天我读到了条件类型,并尝试在一般服务中声明 ApiDataType = any,然后在扩展服务中用 ApiDataType = UserApiData 覆盖它。但是,您使用泛型的解决方案似乎是正确的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2016-05-11
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多