在哪里放置接口并键入别名

Max*_*kyi 9 angular

我在angular2项目中使用自定义界面并键入别名。例如,我正在实现一个显示产品列表的组件,因此我需要定义 Product接口:

export interface Product {
    id: number;
    name: string;
    price: number;
}
Run Code Online (Sandbox Code Playgroud)

现在我需要一个放置接口的地方。我认为它应该在components文件夹中。我也偷看了源代码,Angular似乎将所有接口都放到了facade文件夹中。因此,我最终得到以下结构:

components
|
|--- product-list
     |
     |--- facade
     |    |
     |    |--- product.ts
     |
     |--- product-list.component.ts
     |--- product-list.component.html
     |--- product-list.component.css
Run Code Online (Sandbox Code Playgroud)

该接口的用法如下:

export class RowComponent implements OnInit {
    @Input() product: Product;
    @Output() productRemoved: EventEmitter<ProductRemoved> = new EventEmitter();

    constructor() {
    }
Run Code Online (Sandbox Code Playgroud)

这是可行的方法吗?是否有特定于该问题的样式指南?

Lin*_*son 6

我也为此感到挣扎。首先要了解的是,目录结构在您的用例和项目复杂性上非常主观。就是说,官方文档有一些良好的入门指南:

https://angular.io/guide/styleguide#style-04-06

对于中型到大型应用程序,我使用以下结构:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- [+] pages
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- [+] authentication
       |-- [+] footer
       |-- [+] guards
       |-- [+] mocks
       |-- [+] models // <- here
       |-- [+] validators
       |-- [+] services
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |
     |-- shared
          |-- [+] components
          |-- [+] directives
          |-- [+] pipes
     |
     |-- [+] configs
|-- assets
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
Run Code Online (Sandbox Code Playgroud)

大多数时候,您的服务(在核心模块中)将占用您的模型接口,而组件依次将仅通过该服务与建模数据进行通信。在较小的应用程序中,将数据模型接口放在Service文件的顶部最有意义。但是,随着您的应用程序变大,在某些情况下,组件需要数据模型接口而不是服务。

保持数据模型接口提供了最可持续的方法,该方法提供了最佳的“关注点分离”和抽象。

文章将详细介绍结构角6级的应用程序。


Sea*_*uit 4

恕我直言,最简单的解决方案是将其放置在模型类上方的同一文件中。

interface ProductJson {
   id: number;
   name: string;
   price: number;
}

export class Product{
    constructor(private id:number,
                private name:String,
                private price:number){}


    public static fromJson(productJson : ProductJson ) : Product {
           //
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:至于文件夹结构:

 product-list
 |
 |--- component
 |    |
 |    |--- product-list.component.ts
 |    |--- product-list.component.html
 |    |--- product-list.component.css
 |
 |--- model
 |    |
 |    |--- product.ts
 |
 |--- service
      |
      |--- product-service.ts
Run Code Online (Sandbox Code Playgroud)

ETC..

这就是我所做的。

  • 谢谢,但是这样接口就不能复用了 (2认同)