当使用 Angular 2 与 rest api 交互时。是否值得为每个对象(例如员工、公司、项目、用户...)创建 typescript 类。另一种选择是获取 json 对象并即时使用它?
最佳答案
我建议使用模型,因为:
- 你的代码在一段时间后回来更改它对你自己来说将更具可读性,其他人也可以很容易地理解你所做的事情
- 在项目中进行更改会更容易,例如 obj[0] 没有任何特殊含义,但 obj['username'] 更明显
- 您将在您的 IDE 中获得智能感知
例如,您可以将逻辑放在模型中,这样您的 Controller 会更薄
name: string age: number sayInfo(): string { return `name is ${this.name} and age is ${this.age}` }
通常,管理您的应用程序不会让人头疼(或者至少不会让人头疼):D
请记住,肥胖模型瘦 Controller
不要忘记将超过五个参数传递给函数不是一个好习惯,例如使用对象代替:
constructor(file) {
this.id = file['id']
this.fileName = file['fileName']
this.extention = file['extention']
this.fileSize = file['fileSize']
this.permission = file['permission']
this.description = file['description']
this.password = file['password']
this.isFolder = file['isFolder']
this.parent = file['parent']
this.banStat = file['banStat']
this.tinyLink = file['tinyLink']
}
getName(): string {
return `${this.fileName}${(this.isFolder) ? '' : '.'}${this.extention}`
}
getIcon(): string {
return this.isFolder ? 'fa-folder' : 'fa-music'
}
关于rest - Angular 2 创建模型与动态处理 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723684/