How to fix Angular Service ngOnInit() not being called
Problem:
You have an Angular service implementing OnInit:
my-service.ts
import { Injectable, OnInit } from '@angular/core';
@Injectable()
export class MyService implements OnInit {
constructor() { }
ngOnInit() {
console.log("MyService initializing");
}
}but it never prints MyService initializing - i.e. the ngOnInit() function is never actually being called.
Solution
Services should not implement OnInit, the function is deliberately never called. Instead, add the code from ngOnInit() in the constructor() and remove implements OnInit and ngOnInit():
my-service.ts
import { Injectable, OnInit } from '@angular/core';
@Injectable()
export class MyService {
constructor() {
console.log("MyService initializing");
}
}Check out similar posts by category:
Angular, Typescript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow