在Ember中获取当前路由名称

17
我需要在我的Ember应用程序中获取当前路由名称;我尝试过这个方法:Ember App.Router.router.currentState undefined,但它对我不起作用(可能是我漏掉了什么...)。我使用的是Ember rc6版本,并且我有一个多语言应用程序;在applicationRoute中,我检测浏览器的语言,并使用以下代码将其重定向到正确的页面:this.transitionTo(userLang); 但我希望仅当用户在首页时才执行此操作,因此类似以下的代码:
if (currentRoute == 'home'){
  this.transitionTo(userLang)
}

11个回答

-2
你可以简单地解析当前的URL。这样,你就可以使用完整的URL,例如:
http://127.0.0.1:8000/index.html/#/home

从这个字符串中提取后缀:

/home

这是当前路由名称。

一个简单的JS函数(无论您使用的Ember版本)如下:

function getCurrentRoute()
{
    var currentRoute;
    var currentUrl = window.location.href; // 'http://127.0.0.1:8000/index.html/#/home'

    var indexOfHash = currentUrl.indexOf('#');
    if ((indexOfHash == -1) ||
        (indexOfHash == currentUrl.length - 1))
    {
        currentRoute = '/';
    }
    else
    {
        currentRoute = currentUrl.slice(indexOfHash + 1); // '/home'
    }

    return currentRoute;
}

使用示例:

if (getCurrentRoute() == '/home')
{
// ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接