Leverage one Injectable service within another Injectable service in Angular 5

I am facing difficulties in utilizing an Injectable service within another Injectable service in Angular 5. Below is my crudService.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class CrudService
{
    constructor(
        private http: HttpClient
    ) { }

    postItem(url: any, body: any, headers?: any, params?: any)
    {
        return this.http.post<any>(url,
            body,
            {
                headers, params
            }
        );
    }
}

Next is my authentication.service.ts where I am incorporating the crudService.ts file:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpClientModule } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { CrudService } from "../common/services/crudservice";

@Injectable()
export class AuthenticationService {
    constructor(
        private http: HttpClient,
        private crudService: CrudService
    ) { }

    login(username: string, password: string) {
        let url = "example";
        let body = "example";
        let headers = "example";
        return this.crudService.postItem(url, body, headers);
    }
}

In my app.module.ts file, only the CrudService class has been imported:

import { CrudService } from "./common/services/crudService";
@NgModule({
    imports: [
        ...
    ],
    declarations: [
        ...
    ],
    providers: [
        ...,
        CrudService
    ],
    bootstrap: [AppComponent]
})

The CrudService @Injectable export class is included in the app.module.ts file. I have tested various scenarios like importing two classes (CrudService and AuthenticationService) into app.module.ts simultaneously among other approaches... Although no compilation errors occur, when launching my application, the following error arises:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[LoginComponent -> AuthenticationService]: 
  StaticInjectorError(Platform: core)[LoginComponent -> AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!
Error: StaticInjectorError(AppModule)[LoginComponent -> AuthenticationService]: 
  StaticInjectorError(Platform: core)[LoginComponent -> AuthenticationService]: 
    NullInjectorError: No provider for AuthenticationService!

If anyone has successfully resolved issues related to using one @Injectable() class within another @Injectable() class and registering that logic in app.module.ts for Angular 5, kindly provide me with the necessary information or guidance to enable successful compilation, deployment, and use of @Injectable() classes. For further clarification or details, please feel free to ask. Thank you.

P.S. My AuthenticationService is injected into the LoginComponent class:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../_services/index';
import { CrudService } from "../common/services/crudservice";

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService) { }

    ngOnInit() {

    }


    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
            resp => {

            },
            error => {

            });
    }
}

Answer №1

Shoutout to Alf Moh, DeborahK, and Mark Uretsky for their help. I finally figured it out... I made some changes in my code by removing CrudService from providers in app.module.ts and adding it in login.components.ts:

providers: [AuthenticationService, CrudService]

Here's how login.components.ts looks now :

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../_services/index';
import { CrudService } from "../common/services/crudservice";

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html',
    providers: [AuthenticationService, CrudService]
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService) { }

    ngOnInit() {
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
            resp => {

            },
            error => {

            });
    }
}

Big thanks for all the guidance. I've learned that when using @Injectable() class within another @Injectable() class, both classes need to be declared in the "providers" array of the component where they are being used. Lesson learned!

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

Angular CLI build/serve/test commands task problem matcher in VS Code

In an attempt to set up VS code tasks for Angular CLI commands such as 'ng build', 'ng serve', and 'ng test', I want to generate a list of problems that can be easily navigated when running a CLI command. Currently, I execute ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Tips on showcasing information with ng for in Ionic 2

https://i.sstatic.net/MKIcJ.jpgI am currently working on the thank you page for my project. When the success call is made, it will display both ORDER DETAILS and Delivery Details. However, in the event of a failure call, only the ORDER DETAILS are displaye ...

Issue in TypeScript: Property '0' is not found in the type

I have the following interface set up: export interface Details { Name: [{ First: string; Last: string; }]; } Within my code, I am using an observable configuration variable: Configuration: KnockoutObservable<Details> = ko.observable& ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

Having difficulty mastering the redux-form component typing

I am facing an issue while trying to export my component A by utilizing redux-form for accessing the form-state, which is primarily populated by another component. During the export process, I encountered this typing error: TS2322 Type A is not assignabl ...

Is there a way to manipulate data being passed to a subject.next() in RXJS before emitting it again?

I have a feeling that this question is going to reveal some gaps in my understanding of observables, but I'll ask it anyway. I want to create an RXJS subject that performs operations on the data before emitting it again. Let me explain with a simple ...

Implement functionality to update the user interface with raw data received through Bluetooth serial communication

I've been utilizing the plugin https://github.com/don/BluetoothSerial to handle my Bluetooth connection with a HC-06 module on an Arduino Leonardo. Everything is functioning well, except for an issue I am encountering with the mobile application. Here ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

"Utilize a callback function that includes the choice of an additional second

Concern I am seeking a basic function that can receive a callback with either 1 or 2 arguments. If a callback with only 1 argument is provided, the function should automatically generate the second argument internally. If a callback with 2 arguments is s ...

Should the PHP interface be exported to a Typescript interface, or should it be vice versa?

As I delve into Typescript, I find myself coding backend in PHP for my current contract. In recent projects, I have created Typescript interfaces for the AJAX responses generated by my backend code. This ensures clarity for the frontend developer, whether ...

How to Import External Libraries into Angular 2

I am attempting to import a 3rd party library called synaptic. This library is written in JavaScript and I have a .d.ts file for it. Here are the steps I have taken: npm install synaptic --save npm install @types/synaptic --save I have also added the fol ...

Experiencing a strange response while attempting to parse the result of an Angular 2 HTTP JSON request

After successfully implementing the http.get call and retrieving data from the request, I encountered an issue: this.http.get('https://data.cityofnewyork.us/resource/xx67-kt59.json').subscribe(data => { // Read the result field from the ...

Mastering the TypeScript syntax for executing the MongoDB find method

Having trouble properly typing the find method of MongoDB in my TypeScript project that involves MongoDB. Here's the snippet I'm working on: import { ReitsType } from '@/app/api/types/reits'; import { NextRequest, NextResponse } from &a ...

How to display a page outside the router-outlet in angular 4

I'm currently developing an angular 4 application and I am trying to figure out how to load the login.page.ts outside of the router-outlet This is what my home.component.html file looks like: <div class="container"> <top-nav-bar></ ...

Creating secure RSA keys using a predetermined seed - a step-by-step guide

Is it possible to utilize a unique set of words as a seed in order to recover a lost private key, similar to how cryptocurrency wallets function? This method can be particularly beneficial for end-to-end encryption among clients, where keys are generated o ...

Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array: const arr1 = [ { "Param1": "20", "Param2": ""8", "Param3": "11", "Param4": "4", "Param5": "18", ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

Guide on creating a dash-patterned line over a rectangle using PixiJS and Angular

In this example, we are creating a PixiJS application that draws a solid-stroked rectangle. Unfortunately, PIXI.Graphics does not have a built-in feature to draw dashed strokes. import { Component, OnInit } from '@angular/core'; import * ...

Determining Refresh Status in Angular Application

Does Angular provide a method to determine if the browser has been refreshed? I need to verify whether the page has been refreshed or not, as I want to run a function only when the value is false. In my ngOnInit function, I have the following code: pageIs ...