Overriding a shared module service in Angular from a separate module: A step-by-step guide

I am working with various modules such as SchoolModule, UniversityModule, and SharedModule

The SharedModule includes a BaseService that both the SchoolModule and UniversityModule providers are utilizing as an extension

When loading the SchoolModule, I need the implementation of the schoolService to be passed to the BaseService, and the same is required for the UniversityModule

Project Structure

app
  -- SharedModule
       -- base.service
       -- secret.service uses base.service
       -- shared.component uses secret.service

  -- SchoolModule
       -- school.component uses shared.component
       -- school.service

 -- UniversityModule
        -- university.component uses shared.component
        -- university.service

Check out the StackBlitz example

How can I achieve this using Dependency Injection?

Answer №1

It is essential to define your primary service class as an abstract class containing a method named getName()

export abstract class MainService{


    abstract getName(): string { return 'Main Service' }


}

export class UniversityService extends MainService{

   getName(): string { return 'University Service' }

}

Answer №2

Regrettably, Angular2 lacks the ability to inject a class from another module without requiring imports between modules. This becomes even more challenging when attempting to lazy load the module. Fortunately, there exists a solution that allows for dynamic loading of components from other modules. While integrating this solution into your project may pose some difficulties, it ultimately prevents redundant coding efforts.
To learn more about this project, visit this link.

Answer №3

A challenge arises with the SecretService provided, as it is built using the UniversityModule's last imported module in the App Module. To update SecretService correctly with BaseService, both BaseService and SecretService must be provided in the university and school components like so in school.component.ts:

import { SchoolService } from './school.service'
import { BaseService } from '../shared/base.service'
import { SecretService } from '../shared/secret.service'

@Component({
  selector: 'app-school',
  template: `SchoolName :: <app-shared></app-shared>`,
  providers: [
    { provide: BaseService, useClass: SchoolService },
    SecretService]
})
export class SchoolComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

In university.component.ts:

import { UniversityService } from './university.service'
import { BaseService } from '../shared/base.service'
import { SecretService } from '../shared/secret.service'

@Component({
  selector: 'app-university',
  template: `UniversityName :: <app-shared></app-shared>`,
  providers: [{ provide: BaseService, useClass: UniversityService },
  SecretService]
})
export class UniversityComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

However, it may be more efficient to use BaseService directly in the shared component instead of wrapping it in SecretService.

Consider using BaseService directly in shared.component.ts:

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

@Component({
  selector: 'app-shared',
  template: `{{name}}`
})
export class SharedComponent implements OnInit {

  name: string
  constructor(private ss: BaseService) {
    this.name = ss.getName()
  }

  ngOnInit() {
  }

}

By utilizing BaseService in this manner, the injection issue can be resolved without relying on SecretService as a workaround.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrolling to top using jQuery - Problem with incorrect anchor

I am attempting to implement a scrollTop animation that scrolls to an anchor within a fullscreen <section>. However, the issue is that it does not scroll to the correct anchor on the first click. Below is the code snippet. <nav id="scroller"> ...

What is the best method for determining the color of the active angular theme for a particular component, such as the hover background of a button?

When using Angular 7 and material design to display a list, I encountered an issue with hover colors. The preset $primary, $accent, and $warn colors were not working well for this purpose. I wanted the hover color of the list items to match that of a butto ...

Linking Angular 2 Production Mode to the vendor directory

I am currently working on an Angular2 project using the angular-cli npm package. To upload the app to the server, I used the following commands: ng build --prod and ng serve --prod. However, after uploading the dist folder to the server and trying to acc ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

Is it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept. I c ...

When performing an arithmetic operation, the right operand must be a data type of 'any', 'number', 'bigint', or an enumeration type

My JavaScript code needs to be converted to TypeScript for proper functionality. categoryAxis.renderer.labels.template.adapter.add("dy", function(dy, target) { if (target.dataItem && target.dataItem.index % 2 === 0) { return dy + 25; } ...

Using System.import in my code is triggering a cascade of errors in my console

I incorporate the System module in my component. export class LoginComponent { constructor() { System.import('app/login/login.js'); } } The file loads successfully, however, TypeScript compiler raises an error Error:(10, 9) TS2 ...

Tips for troubleshooting compile errors when updating an Angular project from version 6 to 7

I am currently working on upgrading my Angular 6 project to Angular 10, following the recommended approach of going through one major version at a time. Right now, I am in the process of updating it to version 7.3. Despite following the steps provided on u ...

JavaScript encounters difficulty in reading the text file

I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using: <html> <head> ...

Executing Sequential Jquery Functions in ASP.Net

I have successfully implemented two JQuery functions for Gridview in ASP.Net 1. Enhancing Gridview Header and Enabling Auto Scrollbars <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script& ...

Facing a challenge with handling HTTP data in a TypeScript-based Angular web application

I am currently working on developing a web application using Angular and the SpringMVC Framework. One of the tasks I'm facing is loading a list of users (referred to as "consulenti" in the code). While the backend HTTP request works fine, I encounter ...

I successfully managed to ensure that the splash screen is only displayed upon the initial page load. However, I am now encountering an issue where it fails to load again after I close the page. Is there any possible solution

After successfully implementing a splash screen that only plays once on page load, I encountered an issue. When I close the tab and revisit the page, the splash screen no longer plays. Is there a way to fix this problem? Perhaps by setting a time limit for ...

How to Use Attributes as Component Parameters in Vue.js

I am currently developing a test Component using Vue.js. I am trying to pass a parameter to be used in my template like this: Vue.component('test', { props: ['href'], template: '<li><a href="{{href}}"><slot> ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Using knockoutjs to call a component on the home page

I am currently facing some challenges with knockoutjs components, as I am following the guidance provided in the official knockout component documentation. Could someone please advise me on how to correctly invoke my widget component on the main page? It ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...