Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 creating models vs working with json objects on the fly?

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 ?

like image 846
user2080105 Avatar asked Jan 18 '17 15:01

user2080105


People also ask

Why do we use models in angular?

One of the primary uses of the model in an MVC application is to provide the data displayed in the view and implement the functions invoked from the view. In an AngularJS application the data binding statements are evaluated against the current scope.

How do you create a type for a complex JSON object in TypeScript?

After TypeScript 3.7 we can also define it in a confined way: type JSONValue = | string | number | boolean | { [x: string]: JSONValue } | Array<JSONValue>; JSONValue circularly references itself. Happy coding!

How do you represent a JSON object in TypeScript?

In Typescript, there are two types of objects. Plain objects: When we try to parse JSON data using JSON. parse() method then we get a plain object and not a class object. Class(constructor) objects: A class object is an instance of a Typescript class with own defined properties, constructors and methods.


1 Answers

i suggest using models because :

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

    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'
  }
like image 198
Amir Ghezelbash Avatar answered Oct 25 '22 21:10

Amir Ghezelbash