How to get a Router instance in an initializer

I have a use case where I want to dynamically register routes in an initializer. Since the application is a self-determining application, I don't know the routes at design time.

Currently I have created an instance initializer:

import Ember from 'ember';
const myTempRouteList = ['home']; // this is retrieved from the backend

export function initialize(instance) {
  let container = instance.container;
  let router = container.lookup('router:main');

  myTempRouteList.forEach(function (name) {
    let routeName = name.dasherize();

    router.map(function(){ // router.map is undefined here
      this.resource(routeName, {path: routeName});
    });
    container.register(`route:${routeName}`, Ember.Route.extend({
    }));

  }, this);
}

export default {
  name: 'register-routes',
  initialize: initialize
};

      

The problem is that the router instance is present but has no method map

. It is described in the documentation as a public method. Some other methods that I checked are present, fi hasRoute

.

+3


source to share


2 answers


It turns out I had to call a method lookupFactory

instead of a method lookup

in the container.



export function initialize(instance) {
  let container = instance.container;
  let router = container.lookupFactory('router:main');

  ...
}

      

+3


source


For people who are running the latest ember with ember-cli (Ember> 2.0). This might be helpful



//initializer.js

export function initialize(application) {
    var routeNames = [];
    var router = application.__container__.lookupFactory('router:main');
    application.deferReadiness();

   //if you want to have your custom routes on the highest level
    if (routeNames.length > 0) {
        router.map(function() {
            var _this = this;
            routeNames.forEach(function(item,index) {
               _this.route(item);
            });
        });
    }

   //if you want to have your custom routes as a child of another parent route
    if (routeNames.length > 0) {
        router.map(function() {
            this.route('parentRoute', {path:'/'}, function(){
                var _this = this;
                routeNames.forEach(function(item,index) {
                    _this.route(item);
                });
            });
        });
    }

    application.advanceReadiness();
}

      

0


source







All Articles