Is injecting & using the router in a component a terrible idea?


#1

I’ve got a component that only ever needs to transition to one route upon it being clicked/submitted, so to keep all these responsibilities in one place, I’m currently injecting the router into the component and calling router.transitionTo('some.route.name') within the component. Is this a bad idea? Are events not going to happen that should do?

This StackOverflow post contains the component-router-injector and related code I’m using:


#2

Hi Eliot,

The most direct way of doing this would be to tie an action to your component and handle that action in you route. See example below. Can you tell why this is not good enough in your case?

// in your template
{{my-component action='goSomeplace'}}

// in the route class
actions: {
  goSomeplace() { this.transitionTo('some.place'); }
}

Update: Having now read your SO post I see your reasoning there. Sorry for rushing in.


#3

Thanks @antigremlin for the original answer and the update. Its good to know that’s the way to do it if the situation requires a custom action.

To give a bit more background to why I’m doing this - I tried delegating to a route originally and found it less understandable than using transitionTo directly in the component.

Something bugged me about it - it felt like indirection for the sake of it, that gets in the way of writing an understandable component.

For now I’m planning on only using actions & routes when the component requires the flexibiity. If it doesn’t I’m going to favour the router injection approach, unless its disovered why that’s a bad idea. I wonder if I’m missing some vital piece of the Ember puzzle that explains why you shouldn’t use router.transitionTo(...) directly in a component.


#4

I’ve looked into the source code for the LinkComponent. Looks like it is not such a bad idea if the basic linking mechanism is using it. The relevant source is here:

Explicit injection of the routing service is used so transitionTo can be used later:

inject.service('-routing')

#5

links are broken, is this still a thing in ember 2.0? i need to inject the router into a service