Angular 2创建模型与动态处理json对象吗? [英] Angular 2 creating models vs working with json objects on the fly?

查看:113
本文介绍了Angular 2创建模型与动态处理json对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Angular 2与rest api交互时,是否值得为每个对象(例如,员工,公司,项目,用户...)创建打字稿类.另一个选择是获取json对象并即时使用它?

when interacting with a rest api using Angular 2. Is it worth creating typescript classes for each object (eg. employee, company, project, user ...). the other option is getting json object and working with it on the fly ?

推荐答案

我建议使用模型,因为:

i suggest using models because :

  1. 一段时间后回来修改代码,您自己的代码将更具可读性,其他所有人也都可以轻松地了解您所做的事情
  2. 更容易进行项目更改,例如obj [0]没有任何特殊含义,但obj ['username']更明显
  3. 您将在您的IDE中获得智能感知
  4. 例如,您可以在模型中放置逻辑,以便您的控制器更薄

  1. your code will be more readable for yourself after a while coming back to change it, every one else also can easily understand what you've done
  2. making changes in project will be more easily for example obj[0] does not have any special meaning but obj['username'] is more obvious
  3. you will get intellinsense in you IDE
  4. you can put logic in model for example so your controller will be more thin

name: string
age: number

sayInfo(): string {
  return `name is ${this.name} and age is ${this.age}`
}

通常,对您的应用进行管理不会让人头疼(或至少会头疼):D

generally managing you app will be without headache (or at least less headache) :D

请记住,胖模型为瘦控制器建模

just remember that fat models thin controllers

不要忘记向函数传递五个以上的参数不是一个好习惯,例如,使用一个对象:

don't forget that passing more than five arguments to a function is not a good practice use an object instead for example :

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'
  }

这篇关于Angular 2创建模型与动态处理json对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆