Angular2:当路由参数更改时调用方法/ngoninit [英] Angular2 : Call method/ngoninit when parameter of route changes

查看:80
本文介绍了Angular2:当路由参数更改时调用方法/ngoninit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在建立一家网上商店,在我的主页上有一个类别下拉菜单,比如说,父猫A,子猫B和C.

Right now I'm making a kind of web shop, and on my home page I've a dropdown of category Let say parent cat A, and sub cats B and C.

Cat A,B和C均由1种成分CatAComponent表示.当我第一次去那些猫中时,我的ngoninit会被调用,并且页面会显示它需要显示的内容.

Cat A, B and C are all represented by 1 component, CatAComponent. When I go in the first time in one of those cats, my ngoninit gets called and the pages displays what it needs to display.

当我想单击另一只子猫时,我仍然在同一组件上,但是仅更改了路由的一个参数(例如,我在localhost:123/CatA/CatB上,现在我在localhost上:123/CatA/CatC,仅更改了一个参数,因此ngOnInit不会被调用,我的更新方法也不会被调用.)

When I want to click on another sub cat, I'm still on the same component, but only a param of the route changes ( e.g. I was on localhost:123/CatA/CatB, now I'm on localhost:123/CatA/CatC, only a parameter changed so the ngOnInit does not get called and my update method does not get called neither).

有什么办法解决这个问题吗?我无法在视图文件中放置(单击)方法来引用该方法,类别菜单位于另一个viewcomponent中.

Any way to go around this? I can't put a (click) method in my view file to reference the method, the menu for categories is in another viewcomponent.

仅更改参数后,我可以调用NgOnInit吗?

Can I call an NgOnInit when only a parameter has changed?

推荐答案

您必须按以下方式订阅 ActivatedRoute 服务:

You have to subscribe to ActivatedRoute service as follows :

//组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params }   from '@angular/router';

export class YourComponent {
  constructor(
    private route: ActivatedRoute      
  ) {}

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      console.log(params); 
      // this will be called every time route changes
      // so you can perform your functionality here

    });
  }
}

这篇关于Angular2:当路由参数更改时调用方法/ngoninit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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