Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 ngOnInit not working when loading the component first time

I Have a component in Angular 4 that and a template to change the route This component is called but does not load anything no server call. If i put the ngOnInit() method content into constructor it works fine. It seems ngOnInit is not called. Anybody please can help i am working on this since last 2 days.

here is my routing configuration.

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 to configure 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>
like image 573
Vikram Singh Avatar asked Jun 29 '17 14:06

Vikram Singh


1 Answers

You have to overload the ngOnInit function. This doesn't work with arrow functions.

You have to do:

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

Hope i could help.


Update (Additional information thanks to maximus):

While a normal function declaration creates the ngOnInit property on the prototype, an arrow function creates it on the instance.

Angular itself looks only for the hooks on the prototype. which is why your original approach doesn't work as expected.

like image 55
malifa Avatar answered Nov 12 '22 05:11

malifa