简体   繁体   English

Angular2:当路径参数改变时调用方法/ ngoninit

[英]Angular2 : Call method/ngoninit when parameter of route changes

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. 现在我正在制作一种网上商店,在我的主页上我有一个类别的下拉列表示父母猫A和子猫B和C.

Cat A, B and C are all represented by 1 component, CatAComponent. Cat A,B和C均由1组分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. 当我第一次进入其中一只猫时,我的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 ( eg 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). 当我想点击另一个子猫时,我仍然在同一个组件上,但只有一个路径的参数更改(例如我在本地主机:123 / CatA / CatB,现在我在本地主机:123 / CatA / CatC,只更改了一个参数,因此不会调用ngOnInit,也不会调用我的更新方法)。

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. 我不能在我的视图文件中放置(单击)方法来引用该方法,类别的菜单在另一个viewcomponent中。

Can I call an NgOnInit when only a parameter has changed? 只有参数更改后才可以调用NgOnInit吗?

You have to subscribe to ActivatedRoute service as follows : 您必须按如下方式订阅ActivatedRoute服务:

//Component //零件

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

    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM