问题
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 ?
回答1:
i suggest using models because :
- 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
- making changes in project will be more easily for example obj[0] does not have any special meaning but obj['username'] is more obvious
- you will get intellinsense in you IDE
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}` }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'
}
来源:https://stackoverflow.com/questions/41723684/angular-2-creating-models-vs-working-with-json-objects-on-the-fly