Why ngOnInit is not called in Angular service when injected?
Hi! I'm new to Angular and TypeScript, and I've encountered a strange problem. I have a service that should perform some initialization when created. I decided to use Angular hooks, specifically `ngOnInit`, so that this code would run automatically. But it doesn't work — the `ngOnInit` method is simply not called. Here is my code:
```typescript
import { Injectable, OnInit } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService implements OnInit {
public data: any[] = [];
constructor() {
console.log('Constructor called');
}
ngOnInit(): void {
console.log('ngOnInit called');
this.data = ['item1', 'item2'];
}
}
```
I expect that when the service is injected into a component, `ngOnInit` will be called automatically, but in the co
No answers yet.
Log in to leave an answer
Blogs