首页 文章

Angular CLI刷新更改路由上的内容

提问于
浏览
1

我有一个Angular CLI应用程序 .

在应用程序中,我有一个 Map (在右侧)和左侧面板(显示有关路线的当前信息) . 如果我点击 Map ,openlayers会找到最近的要素 and redirects me to /map/routeID/detail . 一切都像魅力一样(在详细信息组件的TS上我从API加载数据,如果没有的话,一切都很好) . 问题是......如果我点击到另一个地方(靠近其他路线) the URL changes (所以我被重定向到另一个路线细节) . But the informations are old (from the other route). 我正在NgOnInit中加载,我试图打印控制台字符串,当我的路线从fox example / map / 1 / detail更改为/ map / 2 / detail时,我发现没有调用NgOnInit .

我怎么处理这个?例如,如果路线改变,则再次触发NgOnInit或类似的事情 .

1 回答

  • 5

    我相信你想要观察路线参数的变化,而不是像评论中那样获得初始值 . 为此,您需要在 ActivatedRoute 对象上订阅其中一个observable(例如 paramMap https://angular.io/api/router/ParamMap),然后运行每次路由更改所需的代码 .

    @Component({...})
    class ExampleComponent {
        constructor(private route: ActivatedRoute) {
        }
    
        ngOnInit() {
            this.route.paramMap.subscribe(map => {
                // run code to process
            });
        }
    }
    

    请注意, paramMap 订阅不需要取消订阅according to the docs(它会自动取消订阅) .

相关问题