Angular ngOnInit默认提供生命周期钩子.
ngOnInit如果我们已经有了,为什么要使用constructor?
以下是Angular 2文档中的一些示例构造函数:
export class AppComponent implements OnInit {
title = 'Tour of heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes() {
this.HeroService.getHeroes().then(heroes => this.heroes = heroes);
}
}
Run Code Online (Sandbox Code Playgroud)
和...
class Car {
constructor(engine, tires, doors){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么以及何时创建一个constructor()角度2 /打字稿(我已经阅读了官方文档,他们为依赖注入和服务创建了一个构造函数).
构造函数,ionViewDidLoad和ngOnInit方法之间有什么区别.在每种情况下哪些行动是适当的.
我的问题涉及从ngrx商店调度和选择.
让我们看看官方示例应用程序中的以下代码:
export class CollectionPageComponent implements OnInit {
books$: Observable<Book[]>;
constructor(private store: Store<fromBooks.State>) {
this.books$ = store.select(fromBooks.getBookCollection);
}
ngOnInit() {
this.store.dispatch(new collection.Load());
}
}
Run Code Online (Sandbox Code Playgroud)
我想了解选择调度ngOnInit和选择的constructor动机是什么.
有人可以提供解释吗?
PS顺便说一下,上面是ngrx示例应用程序的示例代码,可以在这里找到:https://github.com/ngrx/platform/blob/master/example-app/app/books/containers/collection-page .TS