Ember.js: Tutorial — Part 2: Ember Data

Lessons

  1. Ember Data model
  2. Test a model
  3. Load a model in a route
  4. Ember Data store
  5. Work with an adapter and a serializer

1. Ember Data model

1.1. Generate rental model

1.2. Edit rental model

NOTE

  • Ember Data
    1
    is a library to manage data and application state
    • It is built around the idea of organizing app data into model objects
    • Each property are represented by an instance (record) of model class
  • @attr maps a property to a corresponding attribute from JSON data
    • e.g. @attr title from {"data": {"attributes": {"title": "…"}}}
    • An attribute declared with @attr is also implicitly auto-tracked
  • An attribute of an instance can be accessed with standard dot notation
    • e.g. model.title from @attr title
  • An implicit id attribute exists to uniquely identy a model object
    • e.g. model.id from {"data": {"id": "…"}}

2. Test a model

2.1. Edit rental model test

NOTE

  • A model test is also known as unit test
    • Unlike other tests, this test do not render anything
    • It simply instantiates a model object and test it directly
    • A model test file can be generated with ember g model-test <name>
  • Ember Data provides a store service, also known as Ember Data store
    • this.owner.lookup('service:store') API can provide access to it
    • createRecord instantiantes model object

2.2. Run rental model test

3-4. Load a model in a route

IMPORTANT

This section include lessons for:

  • 4. Ember Data store

3-4.1. Edit index route

3-4.2. Edit rental route

NOTE

  • Ember Data store is a service injected into a route with @service store
    • It acts as a middleman between the app and the server
    • It is available as this.store
      • It provides find to fetch one record with model type and model ID
      • It provides findAll to fetch all records with model type
    • It caches response fetched from server
      • e.g. access an existing record without re-fetching data from server

5. Work with an adapter and a serializer

5.1. Generate application adapter

5.2. Edit application adapter

NOTE

  • Add namespace to prefix resource URL
    • e.g. /api/<path>
  • Overriding buildURL to suffix resource URL
    • e.g. /<path>.json

5.3. Generate application serializer

5.4. Destroy application serializer test

IMPORTANT

Delete application serializer test file to prevent test errors in this tutorial.

5.5. Run all tests

NOTE

  • Ember Data uses adapter and serializer architecture
  • An adapter deals with where and how Ember Data should fetch data
    • e.g. HTTP/S, WebSocket, Local Storage, URL, header, parameter, etc.
  • A serializer converts data received from server into an Ember Data format
    • JSON:API
      2
      is its default data protocol and interchange format
    • A JSON:API adapter and serializer are also provided by default
  • Re-visit localhost:4200 and it should still work as before

References

Show Comments