【问题标题】:Angular - What is the most neat way to maintain and structurize interfaces?Angular - 维护和结构化接口的最简洁的方法是什么?
【发布时间】:2019-07-29 07:48:43
【问题描述】:

我正在使用 Ionic / Angular 开发应用程序。为了处理 HTTP 响应,我创建了一个接口来管理 JSON 响应。我在文件底部添加了这个名为interface IOne 的接口。喜欢:

export Class Example { 

  private getExample() {
    this.http.get(url, {}, {}).then((result) => { const data: IOne = result.data; });
    return data;
  }

}  

export interface IOne {
  name: string;
}

将来会创建多个接口,因为我将发出具有不同响应类型的多个 HTTP 请求。这样一来,我的Class Example 下会有一个很长的接口列表,这不整洁(我假设?)它看起来像这样:

export Class Example { }  

export interface IOne {
  name: string;
}

export interface ITwo {
  age: number;
}

export interface IThree {
  color: string;
}

我考虑过创建 1 个名为 interfaces.ts 的文件并将此文件导入 example.ts。这是一个好的解决方案吗?有更好的选择吗?具体来说:

管理和构建多个接口以保持良好的项目结构的最佳方法是什么?

【问题讨论】:

    标签: angular typescript ionic-framework interface


    【解决方案1】:

    如果您使用的是 Angular CLI,那么您可以生成一个库,您可以在其中将一个或多个项目的所有共享资源放在同一结构中。

    只需在您的项目根目录中运行此命令:

    ng generate library shared
    

    现在您将看到一个名为 projects 的新文件夹,其中还有一个 shared 文件夹。

    在这个shared 文件夹中,您可以放置​​您想要的任何内容,然后通过public_api.ts 文件公开它们,您将通过几个示例了解它是如何完成的。

    观看您的 shared 库运行:

    ng build shared --watch
    

    然后在您的主应用程序中导入内容就像这样做一样简单:

    import {MyInterface} from 'shared';
    

    确保运行ng serve 你已经为shared 运行构建命令,否则dist 文件夹中将不存在它,这将导致你的主应用程序显示提示找不到 shared 的错误。

    【讨论】:

      猜你喜欢
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 2011-04-10
      • 2011-12-18
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多