0

我有以下 Angular 6 组件来编辑帖子:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'post-edit',
  templateUrl: './post-edit.component.html',
  styleUrls: ['./post-edit.component.less']
})

export class PostEditComponent implements OnInit {

  @Input() id: number;
  title: string;
  content: string;
  categoryId: number;

  categories: Array<{ id: number, name: string }>;

  constructor() { }

  ngOnInit() {
  }

}

当调用 API 以使用 postId 获取帖子的数据时,它返回:

{
  "data": [
    {
      "postId": 1,
      "title": "post title",
      "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
      "categoryId": 2,
      "created_at": "2018-10-20 10:14:23"
    }
  ]
}

所以我在 Angular 中创建了一个 PostService,如下所示:

@Injectable()
export class PostService {

  constructor(private http: Http) { }

  public get() { }

  public create(post) { }

  public getById(id: number) { }

}

问题 1

我应该按如下方式为每个组件定义一个模型(编辑、列出、创建...)吗?

export class PostEditModel {
  id: number;
  title: string;
  content: string;
  categoryId: number;
}

问题2

保存类别列表以显示在 HTML“选择”上的变量应该categories包含在 PostEditModel 中还是仅包含在组件中?

问题 3

PostEditComponent 或 PostEditModel 中的 Post 属性小于 API 返回的属性(例如:created_at)。

每个服务方法都应该有自己的模型吗?例如:

public getById(id: number) { }

将返回一个 PostServiceGetApiModel,它在被 PostEditComponent 调用时将映射到 PostEditModel。

进行此映射的最佳方法是什么?

基本上,我正在尝试为需要能够扩展的应用程序找到最佳解决方案......

4

2 回答 2

0

答案 1

不。只需一个带有可选字段的模型就足够了。比如add model里面,如果是在线生成的,就不会有id。所以模型可以是:

export interface Post {
  id?: number;
  title: string;
  content: string;
  categoryId: number;
}

请注意,我声明的是 aninterface而不是 a class,因为Angular 建议数据模型是接口而不是类。

考虑使用数据模型的接口。

答案 2

我认为categoryId已经包含在模型中。所以我不确定是否需要在其中包含类别。

但是,我建议您创建一个enumfor 类别只是为了在您分配或使用enums 的地方进行一些强类型化。

答案 3

我认为答案 1也回答了这个问题。Post 模型可以包含与 Post 的任何 CRUD 操作中存在的 post 相关的所有字段。因此,如果在 CRUD 的所有阶段中都存在一些,只需将它们保持为强制性,其余作为可选。所以created_at可以是可选的

于 2018-10-19T11:18:58.583 回答
0

答案 1

每个组件一个模型。无论您现在的Post模块文件是什么,都非常好。

每个模块应该有以下文件: - 组件 - 服务 - 模型 - 模块 - 路由

答案 2

不。

类别,我相信您将在添加/编辑帖子时从中选择单个/多个类别的列表。它应该只在 Post 组件中。另外我认为它应该来自服务 - 后端,因此无需在前端维护列表的更改。

答案 3

不。

我想我们已经在答案 1中介绍了这一点。

建议

除了你的问题=最好只创建包含 PostEditComponent 或 PostAddComponent 的 PostComponent。您可以使用 Angular 轻松处理它。你只需要检查路线中的参数。

于 2018-10-19T12:25:07.543 回答