余烬replaceWith不会更改网址

时间:2019-10-09 13:27:14

标签: ember.js ember-router

如何对同一路径执行某些replaceWith,但参数不同?

路线声明为:

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

此“ sampleRoute”路由重现了该问题:URL在其中replaceWith之后没有更改。

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');
    }
  }
});

尝试过beforeModel,model,afterModel。在运行一些代码之前如何正确设置URL?

使用http://localhost/sampleRoute/browserValue测试此路由会产生:

Expected output: 
    welcome
    welcome
    /sampleRoute/progValue
    progValue

Actual output:
    welcome
    welcome
    /sampleRoute/browserValue
    progValue

1 个答案:

答案 0 :(得分:0)

如果 /sampleRoute/之后的网址段不是动态的,我认为您正在寻找的是嵌套路由,而不是查询参数。您的router.js文件将具有:

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

或者,如果该段是动态的,则您的router.js文件为:

this.route('sampleRoute');

重要的是,您不需要将参数指定为路线的path选项。

在您的模型中,replaceWith将哈希作为查询参数:

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);
    }
  }
});

但是,我想问你在这里想做什么。您应该能够让余烬的路线和控制器为您管理查询参数,而根本不需要replaceWith。我会查看指南:https://guides.emberjs.com/release/routing/query-params/

相关问题