在 Ember 中获取当前路线名称 [英] Get current route name in Ember

查看:35
本文介绍了在 Ember 中获取当前路线名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的 ember 应用程序中获取当前的路由名称;我试过这个:Ember App.Router.router.currentState undefined但它对我不起作用(我可能遗漏了一些东西......)我使用 Ember rc6 并且我有一个多语言应用程序;在 applicationRoute 中,我检测浏览器的语言,然后重定向到正确的页面:

I need to get the current route name in my ember application; I tried this: Ember App.Router.router.currentState undefined but it doesn't work for me (there is probablig something i'm missimg...) I use Ember rc6 and I have a multilingual app; in the applicationRoute I detect the browser's language and I redirect to the correct page with:

this.transitionTo(userLang);

但我希望仅当用户在主页上时才执行此操作,因此如下所示:

but I would like this to be executed only when user are on the home page, so something like this:

if (currentRoute == 'home'){
  this.transitionTo(userLang)
}

推荐答案

注意:从 Ember 3.16 开始,不仅推荐原始答案,而且强烈不鼓励观察者.

NOTE: as of Ember 3.16, the original answer is not only recommended, but observers are strongly discouraged.

要获取当前路由名称,您可以使用路由器服务:https://api.emberjs.com/ember/3.18/classes/RouterService/properties/currentRouteName?anchor=currentRouteName

To get the current route name, you can utilize the Router Service: https://api.emberjs.com/ember/3.18/classes/RouterService/properties/currentRouteName?anchor=currentRouteName

export default class MyComponent extends Component {
  @service router;

  get activeRoute() {
    return this.router.currentRouteName;
  }
}


以下原答案


Original answer below

你可以观察applicationcurrentPath,并在它改变时相应地将其设置为当前路由:

You could observe the application's currentPath and set it to the current route accordingly when it changes:

App = Ember.Application.create({
  currentPath: '',
});

App.ApplicationController = Ember.Controller.extend({
  updateCurrentPath: function() {
    App.set('currentPath', this.get('currentPath'));
  }.observes('currentPath')
}),

通过这种方式,您可以随时使用 App.get('currentPath');

This way you have access to the currentPath when ever you want with App.get('currentPath');

例如

if (App.get('currentPath') == 'home'){
  this.transitionTo(userLang);
}

希望有帮助.

这篇关于在 Ember 中获取当前路线名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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