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

Tan*_*uyB 6 typescript ngoninit angular

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

Cat A,B和C均由1组分CatAComponent表示.当我第一次进入其中一只猫时,我的ngoninit被调用,页面显示它需要显示的内容.

当我想点击另一个子猫时,我仍然在同一个组件上,但只有一个路径的参数更改(例如我在本地主机:123/CatA/CatB,现在我在本地主机:123/CatA/CatC,只更改了一个参数,因此不会调用ngOnInit,也不会调用我的更新方法).

有什么方法可以绕过这个吗?我不能在我的视图文件中放置(单击)方法来引用该方法,类别的菜单在另一个viewcomponent中.

只有参数更改后才可以调用NgOnInit吗?

ran*_*al9 18

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

//零件

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

    });
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案涉及的是参数,而不是整个路径。对于路线,请转到此处/sf/ask/2971736281/ (2认同)