Angular 2:路由参数更改,重新加载同一页面? [英] Angular 2: Route parameter changes, reload the same page?

查看:42
本文介绍了Angular 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,我将无法获取路由参数,也无法调用我的方法来获取用户.

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆