Angular 4 ngOnInit在第一次加载组件时不起作用

Vik*_*ngh 6 javascript angular

我在Angular 4中有一个组件和一个模板来改变路由这个组件被调用但不加载任何没有服务器调用的东西.如果我将ngOnInit()方法内容放入构造函数中,它可以正常工作.似乎没有调用ngOnInit.自从过去2天以来,任何人都可以帮助我解决这个问题.

这是我的路由配置.

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我配置路由的模板

<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>
Run Code Online (Sandbox Code Playgroud)

lex*_*ith 6

你需要overload这个ngOnInit功能.这不适用于箭头功能.

你必须做:

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

希望我能提供帮助.


更新(感谢maximus的其他信息):

正常的函数声明ngOnInit在原型上创建属性,而箭头函数在实例上创建它.

Angular本身 只看原型上的钩子.这就是为什么你的原始方法不能按预期工作的原因.

  • 这是因为角度编译器[搜索原型的钩子](https://github.com/angular/angular/blob/master/packages/core/src/reflection/reflection_capabilities.ts#L205),而不是实例[while](https ://stackoverflow.com/questions/44827678/angular-4-ngoninit-not-working-when-loading-the-component-first-time#comment76636037_44827678)...您可以将此信息添加到您的答案中 (2认同)