在组件的 ngOnInit 方法中,重置需要重置的变量或属性。例如:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
// ...
})
export class MyComponent implements OnInit {
count = 0;
constructor(private router: Router) { }
ngOnInit() {
// 重置 count
this.count = 0;
}
goBack() {
this.router.navigate(['/']);
}
}
在上述代码中,当我们从其它页面返回 MyComponent 页面时,组件会重新初始化,调用 ngOnInit 方法,然后重置 count 属性为 0,确保我们从 0 开始计数。