Search code examples
javascriptangularangular6angular-services

Why is a singleton service instantiated on every route change and not only once in Angular 6?


I have a service which is defined like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, Subscription, combineLatest } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})

export class MyDataService {
  constructor(private http: HttpClient) {
    console.log('Called MyDataService constructor');
  }
}

As far as I understand this service should be singleton throughout the runtime of the apllication.

Now, when the page refreshes, it logs "Called DataService constructor" correctly.

Unfortunately when I navigate to another page (new routes with lazy loading modules) the constructor is run again and it logs "Called DataService constructor" on each route change.

Did I miss something?


Solution

  • providedIn: 'root' means that it will only be instantiated once and the same instance will be provided to all dependency requests. If you are see the constructor run more than once then you are providing it somewhere else. Search for where you are providing it as providedIn: 'root' does not need to be listed in a provides list. Search for "provides : [" and see what is providing the MyDataService and remove it. If you are using VS Code you can right click on the class name and select find all references and see where it is in a provides array.