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

Ways to create a method that can be overridden

Is there a way to declare a virtual method in TypeScript? I'm attempting to achieve something similar to the following: export abstract class SuperClass { public virtual enable(enableComponents: boolean): void { } } ...

Angular 2 - ERROR: The value of 'ngClassUntouched' expression has been modified after the initial check

The error message is as follows: angular2.dev.js:23597 EXCEPTION: Expression 'ngClassUntouched in myComponent@7:12' has been modified after it was checked. Previous value: 'true'. Current value: 'false' in [ngClassUntouched ...

Encountering the "ERR_FILE_NOT_FOUND" message within the popup of my Chrome extension

Currently, my manifest file is structured as follows: { "manifest_version": 2, "name": "My Extension", "description": "A starting point for creating a functional Chrome extension", "version": "0.0.1", "browser_action": { "default_popup": " ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Access JSON value using jQuery by key

Creating a JSON structure that contains information about attendees: { "attendees": [ { "datum": "Tue, 11 Apr 2017 00:00:00 GMT", "name": " Muylaert-Geleir", "prename": "Alexander" }, { "datum": "Wed, 12 Apr 2017 ...

jquery selector to target an element nested inside an anchor tag

Is there a way to use a Jquery selector to extract the text content within the 'name' attribute? <a href="page1.php" id='title' name="<?php echo $res['id'];?>" title="<?php echo $res['title'];?>" < ...

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

Displaying a dropdown selection that showcases two object properties lined up side by side

I need the select option dropdown values to display employee names along with their titles in a lined up format. For instance, if my values are: Bob Smith Director Mike Kawazki HR Jane Doe Manager I want them to be shown as: Bob Smith Director Mi ...

Using Twitter bootstrap with Node.js and Express framework

Is it possible to integrate Twitter Bootstrap with Node.js and Express? I understand that I need to place CSS and Javascript files in the ./public directory (if it's set as default). However, when trying to implement Twitter Bootstrap on Node.js and ...

Transmitting OfficeJS 2D Array via an Ajax Call

Struggling with sending a "large" table using OfficeJS: functionfile.html loaded from manifest route <script> (function (){ "use strict"; Office.initialize = function (reason) { $(document).ready(function() { $("#send-data-button").cli ...

javascript Href and onclick malfunctioning

I am encountering an issue with a form on my webpage: <form name="myForm" id="myForm" method="post" action="someUrl.php"> ... </form> There is a div outside of this form which contains an anchor link: <a href="anotherUrl.php" onclick="doc ...

Identify and react to an unexpected termination of an ajax upload process

My ajax uploading code can determine if a file was successfully uploaded only after the upload has completed. If the upload is terminated before completion, no data is returned. Is there a way to detect when an upload is unexpectedly terminated and alert t ...

The element ion-view is not recognized

Here is the content I have for my Ionic page: <ion-content padding class = ""view-content"> <form> [form content here...] </form> </ion-content> This is the CSS code from my file: .view-content { backg ...

The text is not appearing properly in an HTML file due to issues with

Hi trying to display the text received from the controller's scope. Here's what I have attempted: HTML: <div ng-repeat="item in sResults"></div> Controller JavaScript: $scope.sResults = []; function App( ){ var Label ...

Arrow functions in ECMAScript 6

var createTempItem = id => ({ id: id, name: "Temporary Product" }); I understand that the arrow function above is the same as: var createTempItem = function(id) { return { id: id, name: "Temporary Product" }; }; However, I am ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

What are the best practices for utilizing AngularJS's $sanitize service?

Recently, I stumbled upon a tutorial discussing authentication in AngularJS. The tutorial showcased an AuthenticationService that was structured similarly to this: angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) { ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...