Ember.Router in its current version does not provide tools for handling unknown routes. Time to crack!
Solution 1 - Fast and Dirty
The idea here is as follows. We have the Ember.Router.route(path) method, which is called with the requested (potentially unknown) path. After calling this method, the path to the router is guaranteed to be known. So, if we compare the requested path and the actual path, and they are different, then the requested path is invalid, and we can redirect the user to page 404.
App.Router = Ember.Router.extend({ route: function(path) { this._super(path); var actualPath = this.get("currentState").absoluteRoute(this); if (path !== actualPath) { this.transitionTo("404page"); } } });
This solution is quite expensive. For example, if the current state is "/ a / b / c" and the user wants to go to "/ b / d / e / unknown", the router will dutifully enter the known states "b", "d" and "e", and only then we will drop the path as unknown. It would be nice if we could say this before the actual routing begins.
Solution 2 - Scripts with private methods
Here we check the correctness of this path and only then we tell the router:
App.Router = Ember.Router.extend({ checkPath: function (path) { path = path.replace(this.get('rootURL'), '').replace(/^(?=[^\/])/, "/"); var resolvedStates = this.get("states.root").resolvePath(this, path); var lastState = resolvedStates.get("lastObject"); return lastState.match.remaining == ""; }, route: function(path) { if (this.checkPath(path)) { this._super(path); } else { this.transitionTo("404page"); } } });
This solution also has its drawback - it uses the resolvePath method, which is marked as private. However, I would use this solution, as it is more efficient than the first.
tokarev Oct 12 2018-12-12T00: 00Z
source share