我在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");
}
}
这是我配置路由的模板
<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>
答案 0 :(得分:5)
您必须overload
ngOnInit
功能。这不适用于箭头功能。
你必须这样做:
ngOnInit() {
this.testService.getTest()
.subscribe(
data=>this.testList = <Array<Test>>data,
error=>alert(error)
);
console.log("ngOnInit");
}
希望我能提供帮助。
正常的函数声明在原型上创建ngOnInit
属性时,箭头函数会在实例上创建它。
Angular本身looks only for the hooks on the prototype.这就是为什么你的原始方法没有按预期工作的原因。