Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember - get target url of transition

I am creating an error hook in my Ember.js app to redirect you to the auth service if you are not allowed to view certain content (in other words, if the server returns a 401).

It looks like this:

Ember.Route = Ember.Route.extend({
  error: function(error, transition){
    if (error.status === 401) {
      window.location.replace("https://auth.censored.co.za");
    }
  }

Our auth api works as follows: If you send it a parameter called target (which is a url), it will redirect you back to that target url after you've logged in.

So I want to somehow get the URL of the route the Ember app was trying to transition to.

Then my code will end up something like this

Ember.Route = Ember.Route.extend({
  error: function(error, transition){
    if (error.status === 401) {
      var target = // Your answer here
      window.location.replace("https://auth.censored.co.za?target=" + encodeURIComponent(target));
    }
  }
like image 418
Marco Prins Avatar asked Dec 05 '25 14:12

Marco Prins


1 Answers

I came across a need for this too, and resorted to using some internal APIs. In my case, I wanted to reload the whole app so that if you're switching users there's not data left over from the other user. When I reload the app, I want to put the user at the URL they tried to transition to, but for which they had insufficient privileges. After they authenticate (and thus have the bearer token in localstorage) I wanted to use window.location.replace(url) to get a clean copy of the whole app with the user at the URL implied by the Ember Transition object. But the question was, how do I go from a Transition object to a URL? Here is my solution, which uses the generate method which is a private API of the router:

  let paramsCount = 0;
  let params = {};
  let args = [transition.targetName];
  // Iterate over route segments
  for (let key1 in transition.params) {
    if (transition.params.hasOwnProperty(key1)) {
      let segment = transition.params[key1];
      // Iterate over the params for the route segment.
      for (let key2 in segment) {
        if (segment.hasOwnProperty(key2)) {
          if (segment[key2] != null) {
            params[key2] = segment[key2];
            paramsCount++;
          }
        }
      }
    }
  }
  if (paramsCount > 0) {
    args.push(params);
  }
  let url = router.generate.apply(router, args);

You'll need to get the router somehow either with a container lookup or some other means. I got it by injecting the -routing service which is documented as an API that might be publically exposed in the future (used by link-to), and which happens to have the router as a property.

While messy, perhaps you might find this helpful.

like image 64
Kevin Bullaughey Avatar answered Dec 07 '25 02:12

Kevin Bullaughey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!