How to pass objects around routes in ember.js?

Member

by kadin , in category: Javascript , 5 months ago

How to pass objects around routes in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 5 months ago

@kadin 

In Ember.js, you can pass objects around routes by using the model hook in the Route file. Here is an example of how you can pass an object between routes:

  1. Define the object in the model hook of the specific Route file where you want to pass the object. For example, if you want to pass an object called 'user' from Route A to Route B, you can define it in the model hook of Route A like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// routes/route-a.js
import Route from '@ember/routing/route';

export default class RouteARoute extends Route {
  model() {
    return { 
      user: {
        name: 'John Doe',
        age: 30
      }
    };
  }
}


  1. To access the object in Route B, you can use the model hook and the params argument to access the object passed from Route A. Here is an example of how you can access the 'user' object in Route B:
1
2
3
4
5
6
7
8
// routes/route-b.js
import Route from '@ember/routing/route';

export default class RouteBRoute extends Route {
  model(params) {
    return this.modelFor('route-a').user;
  }
}


  1. You can then access the 'user' object in the template file associated with Route B using the model property:
1
2
3
<!-- templates/route-b.hbs -->
<h1>{{model.name}}</h1>
<p>Age: {{model.age}}</p>


By following these steps, you can easily pass objects between routes in Ember.js.