Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Routing and Templates

Route Classes and the Model Hook

Learn what an Ember route class does - loading data in model(), guarding with beforeModel, redirecting, passing context to children and the order in which route hooks run.

The router decides which routes are active. A route class decides what each one does: which data to load, whether the visitor may see the page at all, and where to send them if not. Routes live in app/routes/ and the file path mirrors the route name, so posts.post is app/routes/posts/post.js.

Real versus stand-in. The route classes below are real Ember code and are read-only here. The runnable blocks reproduce the hook order and the promise handling in plain JavaScript so that you can see exactly when each hook runs.

The model hook

The most important method on a route is model(). Whatever it returns becomes the route's model, and the route's template receives it as @model. If it returns a promise, the router waits and only then renders the page.

JavaScript
// app/routes/posts/post.js
import Route from '@ember/routing/route';

export default class PostsPostRoute extends Route {
  async model(params) {
    const response = await fetch(`/api/posts/${params.post_id}`);
    if (!response.ok) {
      throw new Error(`Post ${params.post_id} could not be loaded`);
    }
    return response.json();
  }
}
JavaScript
// app/templates/posts/post.gjs
<template>
  <article>
    <h2>{{@model.title}}</h2>
    <p>{{@model.body}}</p>
  </article>
</template>

If the promise rejects, Ember shows the nearest error substate (see Query Parameters and Loading States). When a route's model is an Ember Data record, you will use this.store instead of fetch; that comes in Ember Data.

Loading several things

Return an object when the page needs more than one resource, and load them in parallel:

JavaScript
async model() {
  const [posts, tags] = await Promise.all([
    fetch('/api/posts').then((r) => r.json()),
    fetch('/api/tags').then((r) => r.json()),
  ]);
  return { posts, tags };
}

The template then uses @model.posts and @model.tags.

The hooks and their order

A route has several hooks, run in a fixed order each time it is entered from a different route:

Hook Purpose
beforeModel(transition) Guard or redirect before loading data (is the user signed in?).
model(params, transition) Load the data.
afterModel(model, transition) Inspect or redirect after the data is known (for example, an empty list).
setupController(controller, model) Hand the model to the controller; usually you do not touch it.
activate() / deactivate() Run once when the route is entered or left.

Parent routes always run their hooks before their children. For /posts/42, application is first, then posts, then posts.post; the router waits for each model() promise before it goes deeper. This ordering lets a child use the parent's data and means a guard in the parent protects the whole subtree.

JS Hook order across a route chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Guarding and redirecting

To send visitors away, call the router service or return a redirect from beforeModel. The modern way is to inject the router service:

JavaScript
// app/routes/admin.js
import Route from '@ember/routing/route';
import { service } from '@ember/service';

export default class AdminRoute extends Route {
  @service session;
  @service router;

  beforeModel(transition) {
    if (!this.session.isSignedIn) {
      this.session.attemptedTransition = transition;
      this.router.transitionTo('login');
    }
  }
}

Calling transitionTo inside a hook aborts the current transition and starts a new one. Because admin is a parent, every child such as admin.users is protected too. You will learn how services like session work in the Services chapter of this track.

Another common redirect sends an index route somewhere else:

JavaScript
// app/routes/index.js
export default class IndexRoute extends Route {
  @service router;

  beforeModel() {
    this.router.replaceWith('posts');
  }
}

replaceWith swaps the current history entry instead of adding one, so the Back button does not return to the redirecting page.

JS A guard that redirects

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Sharing data with child routes

A child can read its parent's model with this.modelFor('parent-route-name'):

JavaScript
// app/routes/posts/post/comments.js
export default class PostsPostCommentsRoute extends Route {
  model() {
    const post = this.modelFor('posts.post');
    return fetch(`/api/posts/${post.id}/comments`).then((r) => r.json());
  }
}

This avoids loading the same record twice. modelFor works for routes already active in the current transition.

Model identity: object versus id

When you navigate with <LinkTo @route="posts.post" @model={{post}}> and pass a whole object, the router skips model() because it already has the data. When you pass only an id (@model={{post.id}}) or visit the URL directly, model(params) runs. Design model() to handle the "only the id is known" case, since that is what happens on reload.

Common mistakes

  • Doing the loading in a component. Put data loading in the route so the router can wait, show loading states and handle errors in one place.
  • Forgetting async/return. If model() does not return the promise, the router will not wait and @model will be undefined.
  • Mutating the model in the template path. Keep model() free of side effects; it may be called again.
  • Redirecting in model(). Guards belong in beforeModel, where no time is wasted loading data you will throw away.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if model() returns a promise?

    The router transition pauses until the promise settles. A rejection leads to an error substate.
  2. 2. Where is the best place for an "is the user signed in?" check?

    beforeModel runs before data is loaded, and a guard on a parent route protects all of its children.
  3. 3. In what order do hooks run for /posts/42?

    The router enters routes outside-in and waits for each model before continuing.
  4. 4. Why does replaceWith matter for redirect routes?

    transitionTo adds a history entry; replaceWith swaps it.
  5. 5. What does this.modelFor('posts.post') return inside a child route?

    It returns the model of an already-active route, which lets children reuse the parent's data.

Summary

  • A route class loads data in model(params); the template receives it as @model, and promises are awaited.
  • Hooks run parent-first: beforeModel, model, afterModel.
  • Guard and redirect in beforeModel with the router service (transitionTo, replaceWith).
  • modelFor shares a parent's model with its children.
  • Passing a whole object to LinkTo skips model(); an id or direct URL visit runs it.

Next: Templates and Handlebars