【问题标题】:Angular2 how to rebuild a view (routing)Angular2如何重建视图(路由)
【发布时间】:2016-11-17 09:09:42
【问题描述】:

如何重建路由器?当我加载同一个路由器但使用另一个参数时,只有 url 发生变化,视图保持不变。有没有办法说路由器 - “嘿,重建你自己!”?

我需要类似window.location.reload() 的效果,但无需重新加载。

【问题讨论】:

    标签: angular angular-routing


    【解决方案1】:

    当您使用不同的参数导航到相同的路线时,它会重用该组件。因此ngOnInit 不会被再次调用,所以您可能认为页面没有更新。您应该在 ngOnInit 中订阅 routeparam,然后在订阅函数中进行视图更新

    在构造函数中注入激活的路由

    constructor(
      private route: ActivatedRoute,
      private router: Router,......) {}
    In the ngOnInit method, we use the ActivatedRoute service to retrieve the parameters for our route
    
    ngOnInit() {
      this.sub = this.route.params.subscribe(params => {
         let id = +params['id']; // (+) converts string 'id' to a number
         //here goes your logic like below
    this.service.getHero(id).then(hero => this.hero = hero);
       });
    }
    

    另外看看另一个soquestion

    【讨论】:

    • 嘿,谢谢。它工作但很奇怪。我是一个路由器回来。就像:点击A -> 没有,点击B -> 重定向到A,点击C -> 重定向到B。你知道哪里错了吗?
    • 向我们展示一些代码,您可能会看到控制台表达式的警告在检查后已更改。尝试将 setter 包装在 setTimeout 中。向我们展示与参数处理相关的代码
    • 对不起,我忘了重构我的代码。我在订阅中使用 this.route.params.snapshot['id'] 而不是 params['id']。谢谢你,你摇滚;)
    猜你喜欢
    • 2016-07-16
    • 2016-09-04
    • 2016-07-13
    • 2016-07-27
    • 1970-01-01
    • 2016-04-30
    • 2017-12-03
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多