这通常是由于组件的生命周期钩子中出现问题所引起的,解决方法是使用子组件和*ngIf在重新路由时重新加载父组件。以下是示例代码:
在父组件中:
在父组件中,我们将创建一个showChild
布尔属性,在重新路由时它将连同子组件重新加载。父组件可以像这样处理路由:
import { Router } from '@angular/router';
// 在constructor中注入路由
constructor(private router: Router){}
// 模拟重新路由
reRoute() {
this.router.navigate(['parent']);
this.showChild = false;
setTimeout(() => {
this.showChild= true;
});
}
在子组件中:
...
在这里,我们将dataLoaded
布尔属性传递给子组件。在子组件的生命周期钩子中,我们将设置为false,并且在订阅数据时将它设置回true。这将确保只有在数据加载完成时才显示组件,而不会出现重新路由时组件未加载的情况。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from '../data.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnDestroy {
dataLoaded = false;
subscription: Subscription;
constructor(private dataService: DataService) {}
ngOnInit() {
// 假设这是订阅我们的数据类型的observable
this.subscription = this.dataService.getData().subscribe(data => {
this.data