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:

https://i.sstatic.net/ob4Ct.png

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

Angular2/Typescript: Transforming a Javascript/Typescript Date into a C# DateTime string on the client side

Currently immersed in an Angular2/Typescript project, I am faced with the task of sending a date to a C# backend. Despite my extensive research, all I could uncover through Google searches was information on converting the date on the backend side. My la ...

Encountered an issue during the transition from Angular 7 to Angular 9

After following the advice in the second response of this discussion, I successfully upgraded to Angular 9. However, I am now encountering an issue in the browser console when running my project. https://i.sstatic.net/esAXf.png Package.json "dependencie ...

Issue with importing Control in Ionic 2 leads to errors

I am encountering an issue when trying to import Control for email Validator in my Ionic 2 RC0 project. Below is the code snippet: /** * Created by adirz on 10/14/2016. */ import { Control } from '@angular/common'; export class EmailValidator ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

The dependency that was installed in the node_modules directory is now showing as missing the

I have encountered an issue with 2 TS packages. The first package, project-1, is installed as a dependency in the second package, project-2. While I am able to import and access all type definitions of project-1 in project-2, the dependencies (node_modules ...

The error message "Property 'chart' is not available in the - ChartJS - Angular 13" indicates that the specified property '

As a beginner in Angular, I am currently working on my first page using Angular and facing some challenges with implementing onClick functionality in ChartJS Bar graphs. The issue arises when attempting to access this.chart within the onClick event of Cha ...

Having trouble rendering Next.JS dynamic pages using router.push()? Find out how to fix routing issues in your

The issue I am facing revolves around the visibility of the navbar component when using route.push(). It appears that the navbar is not showing up on the page, while the rest of the content including the footer is displayed. My goal is to navigate to a dy ...

Ways to transmit additional arguments to RxJS map function

When working with an Angular application, I utilize HttpClient along with RxJS operators to execute various API calls. One example of this is shown below: return this.httpClient.put(url, JSON.stringify(treeOptions)) .pipe( map(this.extract ...

Enhancing the appearance of div content in Angular by utilizing local template variables and material elements

Within this particular implementation, I have utilized an md-sidenav component with a local template variable #sidenavsearchArea. <md-sidenav #sidenavSearchArea align="" mode="push" opened="false"> sidenav content here.. </md-siden ...

Performing several HTTP requests in a for loop in Angular 8

Within the backend, there exists an endless list of cars. Each car is designated by a unique id and has a corresponding model name. I possess a compilation of car IDs, as illustrated below: const carIds = ['abc','xyz']; My objective ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

"Unlocking the Power of Monaco Editor: A Guide to Fetching CompletionItems from Your

Currently, I have integrated the fantastic monaco editor into my Angular 8 app for editing formulas. Everything is working fine, but now I need the list of suggestions (CompletionItems) to update dynamically. I have utilized the ngx-monaco-editor module a ...

A guide to adjusting the size of a mat-button using an svg mat-icon

I have PrimeNg and Angular Materials buttons on the same td. I am attempting to resize my mat-buttons to match the size of my pButtons but they are not adjusting properly. Should I consider using a different type of button with my icon? HTML <button ma ...

Navigating to a precise element within a page in Angular with flawless redirection

I recently encountered an issue where I had to add a span element with a specific ID in my HTML code to ensure that clicking on the Reply button would navigate to it. However, this modification was only necessary for the last element on the page. While the ...

Implementing undefined value acceptance in yup object when using Material-UI

Even though I have clearly specified that the key is optional in my Form, for some reason my input does not accept undefined as a value. Instead, I keep getting this error message: bonusPercentage must be a number type, but the final value was: NaN (cast ...

Having difficulty properly streaming UI components with Vercel's AI-SDK

Recently, I've been diving into the new Vercel's AI-SDK to expand my skills. My current project involves developing a persona generator that takes specific guidelines as inputs and generates persona attributes according to a given Zod schema. B ...

Using Firebase's REST API to send a PATCH request

Greetings, I am currently working on an Angular application that utilizes Firebase. I need to update a record in my database and I am using the REST API for this purpose: this.http.patch(fireBaseConfigDBEndpointCloudReference + this.logIn.getUser().valu ...

Navigating away from the IdentityServer page within the Angular SPA in an ASP.NET Core application triggers a refresh of the entire

My ASP.NET Core Angular SPA app is integrated with IdentityServer 4. Whenever I navigate to the Identity pages (such as Manage Account) and then return to my app (by clicking the Home link or Back button), the website reloads. Is this normal behavior? Can ...

Developing a search feature using Angular 6 with Observable subscription for the FrontEnd application

I have a unique challenge where I need to implement a full text search in the FrontEnd due to restrictions with the API. When the frontend starts up, it fetches all data entries from the Backend and subscribes them inside a component using an async pipe. T ...