Error encountered when initializing a variable within the constructor of a TypeScript file in Angular 4

This is the content of my app.component.html file

PL Auth

Username:

Password :

Generate OTP

Enter OTP :

Login

This is the code in my app.component.ts file

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Headers, Http, Response } from '@angular/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  submitted = false;
  userName = '';

  ngOnInit() {
  }

  constructor(private http: Http;) { }

  private generateOtp(){
    this.http.get('http://localhost:8080/generateotp/'+this.userName)
    .subscribe(
      (res:Response)=> {
        const otpCheck = res.json();
        console.log(otpCheck);
      }
    )
  }

  generateOtpSubmit() {
    this.submitted = true;
    this.generateOtp();
  }
}

This is what's included in my app.module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { Http } from '@angular/http';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [Http],
  bootstrap: [AppComponent]
})
export class AppModule { }

When I attempt to initialize any variables in

constructor(private http: Http;) { }
within app.component.ts file, an error is showing up in the browser console and the page fails to load.

Error: StaticInjectorError(AppModule)[Http -> ConnectionBackend]: 
StaticInjectorError(Platform: core)[Http -> ConnectionBackend]: 
NullInjectorError: No provider for ConnectionBackend!

This is a screenshot of the internal error occurrence:

Answer №1

Starting from Angular version 4.3, it is necessary to import HttpClientModule and include it in the imports section of your code. No separate configuration is required. Keep in mind that this module resides in @angular/common/http. The recommended class for making HTTP requests is HttpClient, as opposed to the outdated Http.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule 
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

However, if you still wish to utilize Http, despite my advice against it, you must import the HttpModule from @angular/http and add it to the imports section. Similar to using HttpClient, no additional providers are needed.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule 
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

Error message "NoSuchKey" encountered on CloudFront when accessing an Angular application

I recently developed an Angular application and successfully uploaded it to an S3 bucket. To make my website accessible, I deployed a CloudFront distribution. However, when trying to access a specific route on the website (such as /login), I encountered an ...

Retrieve a multitude of nested Records within the returnType that correlate with the number of arguments provided to the function

My goal is to dynamically define a deeply nested ReturnType for a function based on the number of arguments passed in the "rest" parameter. For example, if we have: getFormattedDates( dates: Date[], ...rest: string[] // ['AAA', 'BBB&apos ...

I am searching for the RowEnter and RowLeave events in a kendo-grid for Angular 2. Where can I find them

When using an ODATA bound Kendo UI Angular 2 table, I am facing the challenge of needing to save the data that a user edits inline on a per row basis instead of per cell. If only there were RowEnter and RowLeave events available for me to achieve this. Do ...

Experimenting with Typescript, conducting API call tests within Redux actions, mimicking classes with Enzyme, and using Jest

I am facing an issue where I need to mock a class called Api that is utilized within my redux actions. This class is responsible for making axios get and post requests which also need to be mocked. Despite following tutorials on how to mock axios and class ...

Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me? I am cur ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

Angular 5 Directive for Structuring Content

I'm currently in the process of developing a versatile search box component, with the following setup: search.component.html <div class="search-box-container"> <fa-icon class="search-icon" [icon]="faSearch"></fa-icon> <input ...

Is there a substitute for $sce in Angular 7?

Previously, in Angular 1, we utilized $sce to display HTML tags like this: > <p><strong>xyzz</strong> yttryrtyt <span > style="color:#e74c3c">abc</span>.</p> in a user-friendly format. I am now curious about th ...

Code coverage analysis in a node.js TypeScript project consistently shows no coverage metrics

I'm currently working on a backend TypeScript project where I'm aiming to obtain coverage reports for unit test cases. However, Jest is returning empty coverage reports both in the terminal and in the HTML report, with no information provided. Ev ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

Modifying pagination page box color in Angular material

Can anyone provide instructions on how to customize the color of the pagination drop down menu? View example image here ...

Dealing with Scoping Problems in a Typescript d3 Update Tutorial

I'm facing challenges trying to implement the provided bl.ocks example in Typescript (using Angular). This is my implementation in TypeScript: StackBlitz Could anyone offer insights on what might be causing the issues I'm encountering? My initi ...

Angular 2's @ViewChild directive may sometimes yield undefined results

After consulting various related posts and documentation, I am still struggling to achieve the desired outcome with @ViewChild. My main objective is to adjust the scroll position of a div. This particular element is not a component, but a regular div in m ...

Is there a way to integrate TypeScript into the CDN version of Vue?

For specific areas of my project, I am utilizing the Vue CDN. I would like to incorporate Typescript support for these sections as well. However, our technical stack limitations prevent us from using Vue CLI. Is there a method to import Vue.js into a bas ...

Encountering an error when trying to access this.$store.state in a basic Vuex

Encountered an error with return this.$store.state.counter: The property '$store' does not exist on the type 'CreateComponentPublicInstance<{}, {}, {}, { counter(): any; }, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, ...

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Using Angular in conjunction with Azure Durable Functions to implement a retry mechanism for HTTP responses

In my Angular 10 application, I am attempting to integrate Azure Functions. The key is to simplify the Azure function protocol by using a single Observable. Executing an Azure function requires the following steps: Initiate a POST request to the Azure fu ...

Combine form data from a reactive form into a string using interpolation

Currently, I am working with an object that has a string property embedded within it. The string in this property contains interpolation elements. For my user interface, I have implemented a reactive form with an input field. My goal is to display the ent ...

NodeJS can be used to convert JSON data into an XLSX file format and allow for

I am currently working on a project in nodejs where I need to convert JSON data into XLSX format and then download it to the client's browser. I have been using the XLSX npm module to successfully convert the JSON data into a Workbook, however, I am f ...

Building a Dynamic Checkbox Validation Feature in Angular Using Data retrieved from an API

Currently, I have a function that retrieves and displays a list obtained from an API: displayEventTicketDetails() { this.Service .getEventTicketDetails().subscribe((data: any) => { this.eventTicketDetails = data.map(ticket => ticket. ...