How much should a service know about routing?


#1

I’m trying to convert our current authentication controller into a service on the path to Ember 2 compatibility. I’m having some trouble converting the following:

actions: {
  checkCredentials: function() {
    Ember.$.post("/login", {
      user: this.get("email"),
      password: this.get("password")
    }).then(
      this._onCredentialsValid.bind(this),
      this._onCrednetialsInvalid.bind(this)
    );
  }
},

_onCredentialsValid: function(json) {
  if (json.needs_two_factor_auth ) {
    this.transitionToRoute('authentication.two-factor');
    return;
  } else {
    this.get('currentCustomer').setProperties(json.customer);
    this.get('currentUser').setProperties(json.user);
  }
}

That is, the authentication.sign-in controller renders an email/password form. When the user submit it, the controller submits the credentials. If they’re valid, it checks whether two-factor authentication is required. If it is, it redirects to authentication.two-factor.

It can do that redirect because Ember.Controller has transitionTo. But my service won’t have that.

Should I just inject the router into the service in an initializer?

export default {
  name: "add-router-to-auth-service",

  initialize: function(_, app) {
    app.inject('service:authentication', 'router', 'router:main');
  }
};

Or is there some other pattern that would be more appropriate?


#2

I think that might be ok for now. in the future I will expect the router to be just another service (just like the store). We have similar use cases for services needing the router and also link-to depends on it, which makes it super hacky.