Ember transitionToRoute cleanly in a component without sendAction

前端 未结 5 2087
悲&欢浪女
悲&欢浪女 2020-12-28 15:09

How can transitionToRoute be called cleanly from within an Ember component?

It works with injecting a controller into the component and calling the cont

5条回答
  •  心在旅途
    2020-12-28 15:56



    UPDATE Please see the other more recent answers for how to achieve this with less code in newer Ember versions, and vote those up if they work for you - Thanks!



    Inject the router into the components and call this.get('router').transitionTo('some.target.route.name').

    To inject the router into all components, write an initializer at app/initializers/component-router-injector.js with the following contents:

    // app/initializers/component-router-injector.js
    export function initialize(application) {
      // Injects all Ember components with a router object:
      application.inject('component', 'router', 'router:main');
    }
    
    export default {
      name: 'component-router-injector',
      initialize: initialize
    };
    

    Sample usage in a component:

    import Ember from 'ember';
    
    export default Ember.Component.extend({
      actions: {
        submit: function() {
          this.get('router').transitionTo('some.target.route.name');
        }
      }
    });
    

提交回复
热议问题