Reputation: 39444
I have the following Angular component:
export class ListComponent implements OnInit {
showComments: boolean = false;
posts$: Observable<PostModel[]>;
constructor(private postService: PostService) { }
ngOnInit() {
this.posts$ = this.getPosts();
}
getPosts(): Observable<PostModel[]> {
return this.postService.getRecentPosts();
}
}
Should I define posts$
inside the constructor?
That about showComments
default value? Inside ngOnInit
too?
If not, when should I use ngOnInit
?
Upvotes: 0
Views: 151
Reputation: 745
Constructor usage in Angular: In Angular, the constructor is used for injecting dependencies into the component class. Nothing much. And keep the constructor as simple as possible
ngOnInit() method usage in Angular: Angular calls ngOnInit when it finishes creating a component DOM. And we will use constructors to inject all required dependencies and processed input bindings.
It’s a common practice to use ngOnInit to do actual work even though the logic doesn’t depend on DI, DOM or input bindings.
Upvotes: 1