In my ember app (1.0.0 production version) I have a URL structure as follows:
/item
/item/{specific-item-name-defined-in-routes}
The Router mapping looks a little like this:
App.Router.map(function () {
this.resource("item", function () {
this.resource("my-first-item");
this.resource("another-item");
...
});
});
If the user navigates to /item
I want to display a specific post (e.g. /item/my-first-item
). I can do this by using the redirect
method of the route:
App.ItemRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('my-first-item');
}
});
Unfortunately with this approach if I manually type into the address bar the URL /item/another-item
or navigate directly to /item/another-item
the app redirects me to /item/my-first-item
. If I just change between nested routes (i.e. by clicking a link in the app it loads correctly).
How can I get the redirection to work around only when a nested route has not been provided?
Instead of redirecting the item route, add the redirect hook to (the automatically generated) ItemIndexRoute:
App.ItemIndexRoute = Ember.Route.extend({
redirect: function () {
this.transitionTo('my-first-item');
}
});
Mike Grassotti's answer is still correct but I wanted to also add an update about how to achieve this in Ember 2.x with ember-cli when using the new pods application structure. When using pods you need to create an index
folder inside of the desired pod and then you can place a route.js
file inside that index folder so the resolver can find it.
pods
├─ application
│ ├─ route.js
│ ├─ controller.js
│ └─ template.hbs
└─ item
├─ index
│ └─ route.js
├─ my-first-item
│ ├─ route.js
│ ├─ controller.js
│ └─ template.hbs
└── another-item
├─ route.js
├─ controller.js
└─ template.hbs
The pods/item/index/route.js
file from above would be something like:
import Ember from 'ember';
var ItemIndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('my-first-item');
}
});
export default ItemIndexRoute;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With