ember replaceWith does not changes the url

821 views Asked by At

How to perform some replaceWith to the same route but with a different parameter?

The route declaration is:

this.route('sampleRoute', { path: '/:param_name' });

This 'sampleRoute' route reproduces the problem: the URL does not changes after a replaceWith inside it.

let globalFlag = null;

export default Route.extend({
  afterModel() {

    console.log("welcome");

    if(globalFlag){
      console.log(this.router.location.getURL());
      console.log(this.paramsFor(this.routeName).param_name);
    } else {
      globalFlag = true;
      this.replaceWith(this.routeName, 'progValue');
    }
  }
});

Tried with beforeModel, model, afterModel. How to have the URL properly set before running some code?

Testing this route with http://localhost/sampleRoute/browserValue produces:

Expected output: 
    welcome
    welcome
    /sampleRoute/progValue
    progValue

Actual output:
    welcome
    welcome
    /sampleRoute/browserValue
    progValue
1

There are 1 answers

1
Patrick Berkeley On

If the URL segment that comes after /sampleRoute/ is not dynamic, I think you are looking for a nested route instead of a query param. Your router.js file would have:

this.route('sampleRoute', function() {
  this.route('someNestedRoute');
});

Alternatively if the segment is dynamic, then your router.js file to be:

this.route('sampleRoute');

Importantly, you do not need to specify params as a path option to your route.

In your model, replaceWith takes a hash for query params:

import { set } from '@ember/object';

export default Route.extend({
  globalFlag: null,

  beforeModel(transition) {
    super.beforeModel(transition);

    if (this.globalFlag){
      console.log('flag set');
    } else {
      set(this, 'globalFlag', true);
      this.replaceWith(this.routeName, transition.to.queryParams);
    }
  }
});

But I would question what you are trying to do here. You should be able to have ember's route and controller manage query params for you, and not need to replaceWith like this at all. I would check out the guide: https://guides.emberjs.com/release/routing/query-params/