导航回组件时,ngOnInit 不会再次运行?

Posted

技术标签:

【中文标题】导航回组件时,ngOnInit 不会再次运行?【英文标题】:ngOnInit doesn't run again when navigating back to the component? 【发布时间】:2020-05-25 04:50:43 【问题描述】:

我有两个 Angular 6 组件。在其中一个组件中,我有一个简单的div,它显示一个总值,例如:

<div> totalDailyCalories </div>

还有.ts(伪代码):

export class TotalDailyCalories 
  public totalDailyCalories: number = 0;

  ngOnInit() 
    // pseudo code - fetchTotalDailyCalories sends an http req to the 
    // backend and retrieves the total amount of calories
    this.totalDailyCalories = this.fetchTotalDailyCalories
  

然后,如果我导航到另一个可以编辑卡路里总数的组件,然后导航回我的 totalDailyCalories 组件,该值仍然是旧的。我认为ngOnInit 在导航回TotalDailyCalories 后会再次运行,但fetchTotalDailyCalories 根本没有被解雇。当我第一次导航到totalDailyCalories 组件时,它只会触发一次。

如何将totalDailyCalories 更新为最新值?或者换句话说,我怎样才能从我的totalDailyCalories 组件重新运行fetchTotalDailyCalories

【问题讨论】:

您确定不是fetchTotalDailyCalories 工作不正常吗?尝试一些简单的日志记录 (console.log) 来仔细检查 ngOnInit() 是否每次都在运行。只要组件在导航离开时被销毁,它就会在重新导航到时重新创建(并因此重新初始化) 看看medium.com/engineering-on-the-incline/… 【参考方案1】:

你必须在类上使用implements OnInit 并导入它:

import  Component, OnInit  from '@angular/core';

@Component(
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
)
export class HomeComponent implements OnInit 

  constructor(
  ) 

  

  ngOnInit() 
      console.log("component initialized");
  


【讨论】:

以上是关于导航回组件时,ngOnInit 不会再次运行?的主要内容,如果未能解决你的问题,请参考以下文章