Ask Your Question
0

What is the process to retrieve the singleton service as a baseService from a commonModule and as an extended service from AppModule?

asked 2023-04-30 09:59:41 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-30 10:09:01 +0000

qstack gravatar image

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) {}
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-30 09:59:41 +0000

Seen: 10 times

Last updated: Apr 30 '23