我有以下 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。
进行此映射的最佳方法是什么?
基本上,我正在尝试为需要能够扩展的应用程序找到最佳解决方案......