简体   繁体   中英

Can we route from a component in ember js?

I have a component which has a button with an action like {{action 'create'}} and inside the action create i wrote like this.transitionTo('page.new'); But i am getting an exception like Cannot read property 'enter' of undefined can anyone answer please?Just want to know is that possible to route from a component?

The way to do that is to use this.sendAction() from your component and bubble it up to the router. The router can then call this.transitionTo() .

The way link-to does it is by injecting routing _routing: inject.service('-routing'),

https://github.com/emberjs/ember.js/blob/v2.1.0/packages/ember-routing-views/lib/components/link-to.js#L530

Ember.Component is extended from Ember.View and you cant use this.transitionTo in a view. It can be done only through a controller/router.

If you want a transition inside the component on clicking, you could use the link-to helper, but if you still want to be able to handle that action, read: http://emberjs.com/guides/components/handling-user-interaction-with-actions/ and the guide after it.

I found out the answer it is possible.we can use simply use the following code from our components action

App.Router.router.transitionTo('new route');

and we will get a call back for this,in which we can set the new route's model.Use the following code for that.

App.Router.router.transitionTo('your route here').then(function(newRoute){

    newRoute.currentModel.set('property','value');

});

Injection is the last thing you wanna do. The way you communicate actions between routes and components is to use the sendAction Method Send Action

template.hbs

{{your-component  action="nameOfYourRouteAction" }}

route.js

export default Ember.Route.extend({


ratesService: Ember.inject.service(),
  model() {
    //return yourdata
  },


  actions: {
    nameOfYourRouteAction(...args){
        this.transitionTo(...args);
    }
  }
});

in your component.js

import Ember from 'ember';

export default Ember.Component.extend({

    actions: {
        toggleTransition: function(...args) {
            this.sendAction('action', ...args);
        }
    }
});

component.hbs

<button {{action "toggleTransition" 'your route'}}>Change Route</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM