简体   繁体   English

Ember.Route-模型挂钩被调用两次,而不是一个

[英]Ember.Route - Model hook is called twice instead of one

I would like to redirect an incomplete URL to a complete correct URL: 我想将不完整的URL重定向到完整的正确URL:

http://localhost/product/12/a-single-pr -> http://localhost/product/12/a-single-product-name

The problem is that the model hook is called twice instead of one, making two identical requests to retrieve a single object. 问题在于,模型挂钩被调用两次而不是一次,从而发出两个相同的请求来检索单个对象。 Any clues? 有什么线索吗?

routes/product.js 路线/product.js

import Ember from 'ember';

export default Ember.Route.extend({
  afterModel(model, transition) {
    let formatted = model.get('formatted');

    if (transition.params.product.formatted !== formatted) {
      let path = '/product/' + model.id + '/' + formatted;
      this.replaceWith(path, model);
    }
  },
  model(params) {
    return this.get('store').findRecord('product', params.product_id);
  }
});

router.js router.js

...

Router.map(function() {
  this.route('product', {path: '/product/:product_id/*formatted'});
});

...

Ember is working as expected. 灰烬正在按预期工作。

You hit the product route, it fetches the model and then in the afterModel, it redirects back to the product route, which will kick off the route lifecycle again, meaning it will fetch the model again and then call afterModel again. 您点击了产品路线,它将获取模型,然后在afterModel中,它将重定向回到产品路线,这将再次启动路线生命周期,这意味着它将再次获取模型,然后再次调用afterModel。

A different way to approach the problem would be to replace to URL in afterModel instead of redirecting back to the same route. 解决该问题的另一种方法是在afterModel中替换为URL,而不是重定向回相同的路由。

See this StackOverflow answer in order to accomplish that: https://stackoverflow.com/a/3503206/2891906 请参阅此StackOverflow答案以完成此任务: https : //stackoverflow.com/a/3503206/2891906

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM