Setting up a route model

Occasionally, you'll need to retrieve data from a model for a template. The route is responsible for loading the appropriate model. This recipe will go over how to do this.

How to do it...

  1. In a new application, open the router.js file and add a new route. We'll call this route students:
    // app/router.js
    import Ember from 'ember';
    import config from './config/environment';
    
    var Router = Ember.Router.extend({
      location: config.locationType
    });
    
    Router.map(function() {
      this.route('students');
    });
    
    export default Router;

    The students route will retrieve data from the students route handler.

  2. Generate the students route. This will create the students route handler and template:
    $ ember g route students
    
  3. In the students.js file, add a new model that returns a JavaScript object:
    // app/routes/students.js
    import Ember from 'ember';
    
    export default Ember.Route.extend({
        model() {
          return [1,2,3,4,5,6,7];
        }
    });

    The model hook normally returns an Ember Data record. However, it can also return any promise objects, plain JavaScript objects, or arrays. Ember will wait until the data is loaded or the promise is resolved before rending the template.

    For simplicity in our example, we returned an array.

  4. Create a simple each loop in the template to display the data from model:
    // app/templates/students.hbs
    {{#each model as |number|}}
        Number: {{number}}<br>
    {{/each}}

    The each loop will display each number in the array. The model data is returned from the route that we created earlier.

  5. Run ember server and load the route at http://localhost:4200/students. It will look like the following image after it is rendered:
    How to do it...

How it works...

A very important job of a route is loading the model. Models are objects that represent data that your application may present to the user. The route can return an Ember Data record, array, or object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.229.86