首页 文章

如何在Angular应用程序中构建模型和服务?

提问于
浏览
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) { }

}

Question 1

我应该如何定义每个组件的模型(编辑,列表,创建......),如下所示?

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

Question 2

categories 变量,包含类别' list to display on an HTML ' select',是应该包含在PostEditModel中还是只包含在组件中?

Question 3

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

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

public getById(id: number) { }

将返回PostServiceGetApiModel,当PostEditComponent调用时,它将映射到PostEditModel .

这种映射的最佳方法是什么?

基本上我试图找到一个需要能够扩展的应用程序的最佳解决方案...

2 回答

  • 0

    Answer 1

    不 . 只有一个带有可选字段的模型就足够了 . 例如,在添加模型中,如果它是在线生成的,则不会有ID . 所以模型可能是:

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

    请注意,我声明 interface 而不是 class 作为Angular suggests数据模型是接口而不是类 .

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

    Answer 2

    我认为 categoryId 已经包含在模型中 . 所以我需要在那里包含类别 .

    但是,我建议您为类别创建一个 enum ,只是为了在您分配或使用 enum s时进行一些强类型 .

    Answer 3

    我想 Answer 1 也回答了这个问题 . Post模型可以包含与任何Post的CRUD操作中存在的帖子相关的所有字段 . 因此,如果CRUD的所有阶段都存在一些,只需将它们强制保留并作为可选项休息 . 所以 created_at 可以是可选的

  • 0

    Answer 1

    每个组件一个模型 . 无论你现在为 Post 模块的文件是完全正常的 .

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

    Answer 2

    没有 .

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

    Answer 3

    没有 .

    我想我们已经在 Answer 1 中讨论了这个问题 .

    Suggestion

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

相关问题