Angular 4 ngOnInit not working when loading component for the first time

I have an Angular 4 component and a template to change the route This component is called but does not load anything that does not call the server. If I put the content of the ngOnInit () method in the constructor, it works fine. It seems ngOnInit is not being called. Anyone please can help, I've been working on this since the last two days.

here is my routing config.

const testRouting: ModuleWithProviders = RouterModule.forChild([
        { path:'createtest/:id', component:TestComponent, resolve: { test:TestResolver }},
        { path:'createtest', component:TestComponent, resolve: { test:TestResolver }},
        { path:'testlist', component:TestListComponent }
]);


import {Component,OnInit} from '@angular/core'
import {TestService,Test} from '../shared'
import 'rxjs/add/operator/map';
@Component({
    selector:'test-list',
    templateUrl:'./testlist.component.html'
})
export class TestListComponent implements OnInit{
    testList:Array<Test>;
    constructor(private testService:TestService){}
    ngOnInit = ()=>{
        this.testService.getTest()
        .subscribe(
            data=>this.testList = <Array<Test>>data,
            error=>alert(error)
        );
        console.log("ngOnInit");
    }
}

      

And here is my template for setting up routing

<nav class="navbar navbar-light">
  <div class="container">
    <a class="navbar-brand" routerLink="/">SLearn</a>
    <a class="xyz" routerLink="/testlist">Test List</a>
  </div>
</nav>

      

+3


source to share


1 answer


You have to overload

use a function ngOnInit

. This does not work with arrow functions.

You need to do:

ngOnInit() {
    this.testService.getTest()
    .subscribe(
        data=>this.testList = <Array<Test>>data,
        error=>alert(error)
    );
    console.log("ngOnInit");
}

      

Hope I can help.




Update (more info thanks to maximus):

While a normal function declaration creates a property ngOnInit

on the prototype, the arrow function creates it on an instance.

Angular only looks at hooks on the prototype , so your original approach doesn't work as expected.

+3


source







All Articles