简体   繁体   中英

Angular 6 Routing ngOnInit not called

In my angular 6 application, I have created a route to redirect to the ClosureFormComponent as in below code:

export const closureRoutes: Routes = [
    { path: 'closure', component: ClosureFormComponent }
];

In a confirmation dialog component, on button's click I navigate to the component using route:

import { Router } from '@angular/router';
export class ConfirmationDialogComponent implements OnInit {

    constructor(private router: Router) { }

    ngOnInit() {
    }

    onContinueClick() {
        this.router.navigate(['/closure']);
    }

}

And below is the component, I am navigating to:

import { Component, OnInit, NgZone, ChangeDetectorRef } from '@angular/core';
import { CaseServices } from '../../services/case-services.services'
import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-service-closure',
    templateUrl:'closure-form.component.html'
})
export class ClosureFormComponent implements OnInit {
    constructor(private route: ActivatedRoute, private zone: NgZone, private cdr: ChangeDetectorRef, private caseFormDataService: CaseServices) {

    }

    getClosureFormData() {
        this.caseFormDataService.loadClosureFormData(1, '15', 1);
    }

    ngOnInit(): void {
        this.zone.run(() => {
            console.log('closure form loaded');

            this.route.data.subscribe(() => {
                console.log('closure form loaded route');
            });
            this.cdr.detectChanges();
        });
    }
}

Issue is that ngOnInit() (ClosureFormComponent )is not getting fired and no console statement is logged. After searching I assumed it could be zone related issue but still no luck!.

Edit : Weird for me is that component (html) gets displayed in the browser but no statements in console. Not able to get why is it so ?

You have:

onContinueClick() {
    this.router.navigate(['/closure']);
}

It should be

onContinueClick() {
    this.router.navigate(['closure']);
}

navigate() is a relative path routing

Try something like this

onContinueClick() {
    this.router.navigateByUrl('/closure');
}

Try to not use NgZone

When you say "ngOnInit() (ClosureFormComponent )is not getting fired", did you mean if you put console.log() inside your constructor it's fired?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM