Possible to make a route transition inside of a service in Ember?

后端 未结 3 1451
轻奢々
轻奢々 2021-01-12 23:16

I\'m using ember-cli 1.13.8 and I have a service that handles most of my logic. Right now I have a function that listens to whether certain things are true or false and then

相关标签:
3条回答
  • 2021-01-12 23:36

    Ember 1.13:

    Create another service called routing:

    import Ember from 'ember';
    
    export default Ember.Service.extend({
        _router: null,
    
        init() {
            this._super();
    
            this.set('_router', this.get('container').lookup('router:main'));
        },
    
        transitionTo() {
            this.get('_router').transitionTo(...arguments);
        }
    });
    

    Then you can:

    routing: Ember.inject.service(),
    
    goSomewhere() {
        this.get('routing').transitionTo('index');
    }
    
    0 讨论(0)
  • 2021-01-12 23:39

    As of Ember 2.15, there is a public router service for exactly this use case. Just add router: Ember.inject.service(), to your Ember class and call this.get('router').transitionTo(...);, easy!


    Generally this is a bad idea, but in some cases it's easier than passing through route actions in 100 places (personal experience).

    The better way to do this from anywhere is to look the router up on the container:

    Ember.getOwner(this).lookup('router:main').transitionTo(...);
    

    this has to be some container allocated Ember object, which includes components, services, and Ember Data models.

    Note also that if this will be called a lot, you will want to store the router as a property. You can do this in the init hook:

    init() {
      this._super(...arguments);
      this.set('router', Ember.getOwner(this).lookup('router:main'));
    }
    ...
    this.get('router').transitionTo(...);
    

    Ember.getOwner(this) works in Ember 2.3+, prior to that you can use this.get('container') instead.

    0 讨论(0)
  • 2021-01-12 23:53

    You can use the routing service (which is a private API):

    routing: Ember.inject.service('-routing'),
    
    init() {
      ... 
      if(true) {
        console.log("you've won!");
        this.get("routing").transitionTo("congratulations");
      }
    },
    
    0 讨论(0)
提交回复
热议问题