本文介绍了角度2:路线参数更改,是否重新加载同一页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条带有参数的路由,当转到页面/users/123时,其中123是调用ngOnInit的参数,我得到了参数,并调用了我的方法来获得用户.

I have a route with a parameter, when going to the page /users/123 where 123 is the parameter the ngOnInit is called, I get my parameter and I call my method to get the user.

但是,当我在该页面上并单击第二个链接/users/456时,不再调用ngOnInit(因为该页面已被实例化).因此,如果没有ngOnInit,我将无法获取route参数,也无法调用我的方法来获取用户.

However, when I'm on that page and I click a second link /users/456 then the ngOnInit is not called anymore (because that page is already instantiated). So without ngOnInit I can't get the route parameter and can't call my method to get the user.

如果我转到/users/123,然后转到/home,然后转到/users/456,显然可以.

If I go to /users/123, then to /home, then to /users/456, it works obviously.

即使我已经在同一页面上,我必须使用什么来确保始终获得调用参数并获取用户的功能呢?

What do I have to use to make sure the function that gets the parameter and gets the user is ALWAYS called even if I'm already on the same page?

推荐答案

您可以使用订阅服务器route.params来监听参数的更改.

You can use subscriber route.params to listen the param's change.

import { ActivatedRoute } from '@angular/router';

export class DemoPage {
    constructor(private _route: ActivatedRoute) { }
    ngOnInit() {
            this._route.params.forEach(params => {
                    let userId = params["userId"];
                    //call your function, like getUserInfo()
            })
    }
}

这篇关于角度2:路线参数更改,是否重新加载同一页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:06