Ember路由器 - 如何处理404(未找到)路由? [英] Ember Router - How to handle 404 (Not Found) routes?

查看:116
本文介绍了Ember路由器 - 如何处理404(未找到)路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Ember.Router 来处理我的应用程序中的无效路由。

I'm trying to figure out how to handle invalid routes within my application using Ember.Router.

目前,如果我输入无效的路由,例如myapp.com/#FooBarDoesntExist,它将重定向到索引路由('/')。我想要它,如果我可以定义一个notFound或404状态,它将路由,所以我可以通知用户什么发生了。相反,他们被转载在主页上。

Currently if I enter an invalid route, e.g. myapp.com/#FooBarDoesntExist, it will redirect to the index route ('/'). I'd like it if I could define a notFound or 404 state that it would route to so I can inform the user what happend. As opposed to them getting dumped on the home page.

推荐答案

Ember.Router在其当前版本中不提供处理未知的方法路线。时间到了!

Ember.Router in its current version does not provide means to handle unknown routes. Time to hack!

这里的想法如下。我们有 Ember.Router.route(path)方法,它使用请求的(潜在未知的)路径调用。在调用此方法后,路由器的路径被保证是已知的。因此,如果我们比较请求的路径和实际路径,并且它们不同,则所请求的路径无效,我们可能会将用户重定向到404页面。

The idea here is the following. We have the Ember.Router.route(path) method, which is invoked with the requested (potentially unknown) path. After the invocation of this method, the path of the router is guaranteed to be known. So, if we compare the requested path and the actual path and they differ - then the requested path is invalid and we may redirect a user to the 404 page.

  App.Router = Ember.Router.extend({

    route: function(path) {
      this._super(path);
      var actualPath = this.get("currentState").absoluteRoute(this);
      if (path !== actualPath) {
        this.transitionTo("404page");
      }
    }
  });

此解决方案相当昂贵。例如,如果当前状态为/ a / b / c,并且用户想要导航到/ b / d / e / unknown,则路由器将尽可能地输入已知状态b,d和e,只有这样,我们把路径丢弃不明。如果我们可以在实际的路由开始之前告诉这一点,那将是很好的。

This solution is quite expensive. For example, if the current state is "/a/b/c", and a user wants to navigate to "/b/d/e/unknown", the router will dutifully enter known states "b", "d" and "e", and only then we discard the path as unknown. It would be nice if we can tell this before the actual routing starts.

这里我们检查给定路径的有效性,然后才告诉路由器继续:

Here we check the validity of the given path, and only then tell the router to proceed:

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");
  }
}
});

此解决方案也有其缺点 - 它使用 resolvePath 方法被标记为私有。不过,我会使用这个解决方案,因为它比第一个更有效。

This solution also has its drawback - it uses the resolvePath method which is marked as private. Nevertheless, I'd use this solution, since it is more effective than the first one.

这篇关于Ember路由器 - 如何处理404(未找到)路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆