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

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

Exploring the interactivity of Vue3 Composition API props!

Currently, I am monitoring two props on a child component (basicSalaryMin and basicSalaryMax). Once the value changes, my next step is to update a reactive value on the parent component (data.companyModels, which is also passed to the child component as a ...

Working with dual generic parameters in a function

Here is a function I am using: bind<T, K extends keyof T>( data: T[], bindedData: T[], key: K, newKey: string ) { } I'm trying to use two generic parameters, but my attempt here did not work: bind<T, K extends keyof T> ...

The table element fails to display in IE11 due to a rendering issue, displaying the error message: "Render error - TypeError: Object does not support the property or method 'entries'"

As someone new to web app development, I am currently working on a project that involves using Vue cli and antd components, with the additional challenge of ensuring compatibility with IE11. However, I have encountered an issue where IE11 does not render ...

Display all items with pagination in a Material UI Table using React

I have recently implemented pagination in a react data table to handle a large number of entries. I wanted to add an option to display all entries by selecting "all" in the rowsPerPageOptions dropdown menu. Currently, I am able to show the count of all ent ...

Is it possible to leverage AngularJS for incorporating Dependency Injection into my Titanium Mobile Application?

Has this approach been attempted before and is it feasible? Are there alternative methods for incorporating DI into Titanium? In a Titanium Application, where should IOC be initialized and how? Is app.js the most suitable location for the composition root? ...

Mastering the art of Typescript typing

I am attempting to start the REST server for an Aries agent as outlined here: import { startServer } from '@aries-framework/rest' import { Agent } from '@aries-framework/core' import { agentDependencies } from '@aries-framework/nod ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

Injectable error occurred while injecting one @Injectable() into another

I'm encountering an issue with Angular2 Dependency Injection. When attempting to inject one class into another, I am receiving the following error: Error Message: "Cannot resolve all parameters for 'ProductService'(undefined). Make sure tha ...

Utilize the power of AJAX for efficiently sorting search results retrieved from MySQL

I'm in the process of designing a flight search page. The initial page contains a form, and when the submit button is clicked, the search results are displayed on the second page. Here's the link to the first page: To test it out, please follow ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

How can nested json be sorted effectively based on two specific fields?

Example Data: [{ 'ID': objID(abc123), 'Department': 'IT', 'Employees': [ { 'ID': 3, 'StartDate': '24-12-2022T08:30', 'active': true }, { ...

"Enhancing user experience with React.js and Socket.io: dynamically updating list item positions based on

export default class ReactApp extends React.Component { constructor(props) { super(props) this.state = { status: [], services: [] } fetchData((err,opt, data) => { function Exists(l ...

Issues with Ajax response being added to the table

I am encountering a technical problem with my university project. The task assigned by the professor is as follows: We need to create a static table that lists 3 domain names in order to enhance the performance of the domain availability API. <table&g ...

Is it possible for member variables to be reinitialized when clicking on a Component? Are there any alternative methods to prevent this from happening

How can I prevent the productList array in the CartComponent from being reinitialized when clicking on the cart tab after adding items to it through addItem function? export class CartComponent implements OnInit { public productList: any[] = []; ...

Is there a way to make all cards in material ui the same height?

My challenge lies in rendering cards in a grid list using material-ui. Each card comprises an image file at the top and some content in the rest of the space. However, variations in text content cause differences in card height. Despite several attempts, I ...

Angular 5 - Empty array containing objects has a length of zero

In my app.component.ts file, I have an array initialized to load objects in the onInit event: ngOnInit() { this.pages = []; } Within the ngOnInit event, I also have a setInterval method that evaluates an expression every few milliseconds: setInterval(() ...

Experience the magic of a customized cursor that disappears with a simple mouse movement in your website,

I have been experimenting with designing a custom cursor for my website. After finding a design I liked, I made some adjustments to suit my needs. However, an issue I encountered is that when I scroll, the custom cursor also moves away from its original po ...

Typing in Angular's decimal pipe results in inaccurate rounding up

Utilizing the decimal pipe from Angular, here is an example: <input pInputText type="number" [ngModel]="factor | number: '.2'" (ngModelChange)="factor=$event"> Upon loading my page, it correctly displays factor as 50.00 which is set in my ...