What is the difference between ngOnInit and constructor in Angular?
spect Constructor ngOnInit
Purpose Initializes the class Lifecycle hook, called after constructor
Use Case Inject
dependencies
Fetch data, initialize logic
Called By JavaScript engine Angular
Example:
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().subscribe(users => this.users =
users);
}
Real-Time Example:
In a profile component:
- Use constructor to inject ProfileService
- Use ngOnInit to fetch the user's data after initialization