Enhancing Angular 4 classes with dependency injection techniques

Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to allow others to use them without requiring knowledge of their constructors!

After following Petr's suggestion in dependency injection, I attempted to implement it. However, I had to make certain adjustments due to compiler errors, which I assume are a result of differences between angular 4 and angular 5!

Below is the code snippet:

Service Locator:

import {ReflectiveInjector} from "@angular/core";

export class ServiceLocator {
  static injector: ReflectiveInjector;
}

Module importing the serviceLocator:

ServiceLocator.injector = ReflectiveInjector.resolveAndCreate(
      Object.keys(services).map(key => ({
        provide: services[key].provide,
        useClass: services[key].provide,
        deps: services[key].deps
      }))
    );

serviceList:

import {SysFwDatesService} from '../sysDates/sysFwDates.service';
import {MatSnackBar} from '@angular/material';
import {SysFwFormSpecBuilder} from '../uiValidation/SysFwFormSpecBuilder';
import {SysFwHttpApi} from '../http/SysFwHttpApi';


export const services: {[key: string]: {provide: any, deps: any[], useClass?: any}} = {
 'SysFwDatesService': {
    provide: SysFwDatesService,
    deps: []
  },
  'MatSnackBar': {
    provide: MatSnackBar,
    deps: []
  },
  'SysFwFormSpecBuilder': {
    provide: SysFwFormSpecBuilder,
    deps: []
  },
  'SysFwHttpApi': {
    provide: SysFwHttpApi,
    deps: []
  }
}

The implementation appears to be functioning properly, but it seems to have disregarded other providers and now expects all providers to be passed in this manner!

An error message I encountered reads:

No provider for HttpClient! (SysFwDatesService -> SysFwHttpApi -> HttpClient)

Should everything be included in the servicesList? Where am I going wrong?

Everything was functioning correctly before using the injector!

Appreciate your assistance!

Answer №1

element, it is discussed that the hierarchy of dependencies related to the HttpClient defined in the HttpClientModule can be complex to manually list as a single array of providers. The text also mentions how using ReflectiveInjector and Injector to handle Angular modules may not be practical, as parsing a module for its provider hierarchy is already managed internally by Angular itself. The suggestion presented involves creating a custom service locator within the injector of the main module, with an example code snippet provided for demonstration. It emphasizes the importance of leveraging framework tools rather than implementing custom solutions to avoid potential issues like compatibility with lazy loaded modules. Furthermore, the text advises against utilizing this specific service locator approach in real-world applications due to its non-idiomatic nature within the Angular framework. Instead, it recommends following best practices and utilizing Angular's built-in features to ensure smoother functionality in the long run. Additionally, a code example showcasing the usage of @Injectable() in both parent and child classes is provided to highlight the importance of maintaining consistency across different versions of Angular and Angular CLI. Overall, the text stresses the significance of adopting standard practices and leveraging existing framework functionalities to minimize potential complications and ensure optimal performance in Angular applications.

Answer №2

Are you familiar with the concept of explicitly declaring HttpClient as a dependency for SysFwHttpApi? It can be done like so:


'SysFwHttpApi': {
    provide: SysFwHttpApi,
    deps: [HttpClient]
}

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

Attempting to test the PactV3 GraphQL endpoint leads to failure as it is met with a 500 Internal Server Error

Currently, I am facing a challenge with creating a Pact on the consumer side using Pact-JS. I have noticed that in PactJS v3, the .withQuery method has been removed and support for GraphQL testing is not available as well. Although it should be possible t ...

Extract the list of selected item Id's from the HTML table and transfer them to the Controller

I have a table in my ASP.NET MVC project that displays information about file types and IDs (which are hidden) to the user. When the user selects checkboxes and clicks on the "Send Request Mail" button, I need to retrieve the IDs of the selected rows and ...

When a promise is executed, it runs the code synchronously regardless of the promise

Essentially, I have a web application that fetches data from Firebase. Due to the time it takes to retrieve this data, I've implemented promises in JavaScript to ensure my code executes at the appropriate times. Within the function getDataFirebase, in ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...

Creating a Rest API URL in Vue.js by extracting form values

I just finished coding this Vue component: <template> <div> <h2>Search User By ID</h2> <input v-model="userId" type="number" placeholder="modify me" /> <br /> <p v-if="userId.length != 0"> ...

When the user clicks, show a designated search result in a separate container

I've been developing my Angular cocktail application, and I've reached a point where I can display all the cocktails in my database (only showing names). Now, I want to implement a feature where if I click on a specific cocktail, its full content ...

Vue.js combined with Video.js (MPEG-DASH) is throwing an error: (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)

I am facing an issue with Video.js when using it as a component in vue.js. I receive a .mpd link from a server and I want to display the video from that link. Following the example in the documentation of Video.js and Vue integration. Every time I call th ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Ways to remove unnecessary spaces from a JSON Object

I have a generic ajax.post method that takes in data from a function parameter. I'm looking to trim the data properties within the function. Here's the current code snippet: function PostToServer(options) { var defaults = { 'url ...

The constant value being brought in from an internal npm package cannot be determined

I have developed an internal npm package containing shared types and constants. My project is built using TypeScript with "target": "ESNext" and "module": "NodeNext". Within one of my files, I define: export type Su ...

When the enter key is pressed on a child modal dialog, it triggers the enter action on the parent modal dialog in IE11 and

Having two bootstrap modal dialog windows, where one creates the other, is causing a problem. When the enter key is pressed on the child's text input, it triggers an event on the parent as well. If the last focused button on the parent was the one to ...

A Step-by-Step Guide on Modifying the Default Button in Angular2CSV

I am currently utilizing Angular 4 along with the Angular2CSV plugin to transfer data from an Angular page to Microsoft Excel. The process has been successful thus far. However, I am interested in changing the name of the button but am unsure of how to d ...

An Unexpected Typescript Error Occurred While Creating an RxCollection With RxDB

I'm new to RxDB and I've come across a strange Typescript error in my Electron project. Here are the relevant parts of my code: import RxDB, { RxCollection, RxDatabase } from "rxdb"; RxDB.plugin(require("pouchdb-adapter-idb") ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

The Angular SSR feature is throwing errors due to non-ESM modules present in my Express API implementation

In my Angular SSR project, I have set up my Express API to run as part of the SSR service. The app code is located in /src/app, while the API code resides in /src/api. There are some imports of the API code into the app code, primarily for using the same t ...

Hide specific content while displaying a certain element

Creating three buttons, each of which hides all content divs and displays a specific one when clicked. For instance, clicking the second button will only show the content from the second div. function toggleContent(id) { var elements = document.getEl ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...

What circumstances warrant the utilization of an Angular service?

My understanding is that services are utilized for inter and intra component communication to abstract complex data structures. Is it accurate to say that services are exclusively used for persistent data structures? In what scenarios should we avoid usi ...

Are generic constraints leading to type inference selecting the incorrect candidate?

TypeScript Version: 2.6.0-dev.20170826 and 2.4.2 I'm questioning whether I've encountered a TypeScript inference bug or limitation, or if my code is simply incorrect. If the code is valid and it's an issue with type inference, I will repor ...

Show segments of video stream on page using node.js

I am currently exploring Node.js and trying to understand how streams work, so please bear with me if I seem a bit unclear. After reading some beginner notes on streams, I decided to test it out. In my project files, specifically in public/images/videos/S ...