首页 > 解决方案 > is there an OnActivate method for angular?

问题描述

I currently have an angular page which implements ngOnInit().

Currently i am on /home and after clicking the home link it doesn't trigger ngOnInit(), is there any onActivate()?

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

标签: angular

解决方案


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

//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();
        }
    }

}

推荐阅读