是否有角度的OnActivate方法?

时间:2018-06-03 10:57:37

标签: angular

我目前有一个实现ngOnInit()的角度页面。

目前我在/ home并且在点击主页链接后它没有触发ngOnInit(),是否有任何onActivate()?

ngOnInit() {
    this.getPage(1);
}

1 个答案:

答案 0 :(得分:0)

不是一个非常优雅的解决方案,但我解决了它。以下是我提出的代码,以防任何人需要它。随时评论我如何改进代码。谢谢!

//app-routing.module.ts
{
    path: 'home',
    component: HomeComponent,
    data: {
        title: 'Home'
    },
    runGuardsAndResolvers: 'always',
}
...
@NgModule({
    imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
    exports: [RouterModule]
})


//home.component.ts

export class HomeComponent extends OnActivate implements OnInit {
    constructor(public router: Router) {
        super(router);
    }

    initialisePage(): void {
        this.getPage(1);
    }

}

//OnActivate.ts
export class OnActivate {

    navigationSubscription;

    constructor(
        public router: Router
    ) {

        this.navigationSubscription = this.router.events.subscribe((e: any) => {
            if (e instanceof NavigationEnd) {
                this.initialisePage();
            }
        });
    }

    initialisePage() {

    }

    ngOnDestroy() {
        if (this.navigationSubscription) {
            this.navigationSubscription.unsubscribe();
        }
    }

}