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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With