Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To retrieve the singleton service as a baseService from a commonModule, and as an extended service from AppModule, you can follow this process: 1. First, create a commonModule and add the singleton service to it using the "provide" property in the "providers" array. 2. Import the commonModule in the AppModule to make it available to the application. 3. To retrieve the singleton service as a baseService from the commonModule, import the service in the component or provider that requires it using the "Injectable" decorator. 4. To retrieve the singleton service as an extended service from the AppModule, create a new provider in the "providers" array of the AppModule using the "useClass" property and specifying the extended service as the value. 5. Import the extended service in the component or provider that requires it using the "Injectable" decorator.

Example:

common.module.ts:

import { NgModule } from '@angular/core';
import { BaseService } from './base.service';

@NgModule({
  providers: [
    { provide: BaseService, useClass: BaseService }
  ]
})
export class CommonModule {}

app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from './common.module';
import { ExtendedService } from './extended.service';

@NgModule({
  imports: [ BrowserModule, CommonModule ],
  providers: [
    { provide: BaseService, useClass: ExtendedService }
  ]
})
export class AppModule {}

base.component.ts:

import { Component } from '@angular/core';
import { BaseService } from './base.service';

@Component({
  selector: 'app-base',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.css']
})
export class BaseComponent {
  constructor(private baseService: BaseService) {}
}

extended.component.ts:

import { Component } from '@angular/core';
import { ExtendedService } from './extended.service';

@Component({
  selector: 'app-extended',
  templateUrl: './extended.component.html',
  styleUrls: ['./extended.component.css']
})
export class ExtendedComponent {
  constructor(private extendedService: ExtendedService) {}
}