Unable to locate module @angular/common/http (excluding SystemJs)

I am currently working with the visual studio 2017 template for my application. The visual studio 2017 project integrates Angular on the client side and ASP.NET Core MVC on the server side. I've run into an issue while trying to create an HTTP interceptor, specifically with TypeScript not being able to load the module. See the code snippet below:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpInterceptor
} from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

I have already installed the necessary module via npm. Here's a glimpse of my package.json file:

    {
      "name": "MYAPP",
     "private": true,
  "version": "0.0.0",
  "scripts": {
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    // List of dependencies
  },
  "devDependencies": {
    // List of dev dependencies
  }
}

Any idea why TypeScript is unable to locate the required module?

Thank you, B

Answer №1

It has come to my attention that you are using [email protected]. To stay current, it is recommended to upgrade Angular as the @angular/common/http module was introduced in Angular 4.3.x

Once you have completed the update (npm update), ensure you have imported the HttpClientModule:

app.module.ts

import { HttpClientModule } from '@angular/common/http';

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

[Edit]

It is important to use @angular/common/http, as it represents the latest version of http. If you are following an Angular 2 tutorial that utilizes the older http module:

To use the older module:

npm install @angular/http

Next, import the module:

import { HttpModule } from '@angular/common/http';

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

There are two distinct methods for implementing interceptors - the traditional approach using @angular/http and the modern approach using @angular/common/http. It is important to note that an @angular2 tutorial may not align with the implementation of an interceptor in @angular4.

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

The npm update command seems to be disregard the information provided by npm outdated

After running npm outdated on my project, I discovered that there were multiple outdated packages. Subsequently, I executed npm update, which successfully updated some of the packages but not all. Even after running npm outdated again, the remaining outdat ...

How can we access child components in vanilla JavaScript without using ng2's @ViewChild or @ContentChild decorators?

Recently, I delved into the world of using ViewChildren and ContentChildren in Angular 2. It got me thinking - can these be implemented in ES6 without TypeScript annotations? The TypeScript syntax, according to the official documentation, looks something ...

Module not located following the completion of project compilation

Below is the content of my package.json file: { "main": "./build/app.js", "types": "./build/app.d.ts", "scripts": { "start": "tsc && node build/app.js", "dev": "concurrently \"tsc -w \" \"nodemon ...

Issues with installing mongoose on Windows 7 using npm

Struggling to set up mongoose on Windows 7, I've exhausted all resources on Stack Overflow related to my issues with no success. Upgraded npm version to 2.4.1 If anyone can offer assistance, it would be greatly appreciated. Here is the error log: F ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...

What is the best method for integrating a static mapping file into a nodeJS module?

Let's say I have a nodeJS module with an index.js file structured like this: module.exports = function() { var map = {}, CSV_FILE = "./input.csv", _loadCSV = function() { var fs = require('fs'), ...

The 'IncomingHttpHeaders' type cannot be assigned to the 'BusboyHeaders' type

I am currently using the busboy module in my TypeScript/Node project for file uploading. In all the documentation for busboy, they suggest initializing it with request headers. However, I am encountering the following error: Type 'IncomingHttpHeaders& ...

What is the command to display a list of all globally installed npm packages using yarn?

Is there a way to list all globally installed npm packages using yarn? As a beginner with yarn, I typically use npm list -g --depth=0 to see all global npm packages. Is there a similar command in yarn for this task? ...

Deactivate the button permanently upon a single click

In the project I'm working on, there is a verification page for e-mail addresses. When new users register, they are sent an e-mail with a link to verify their e-mail. If the link is not clicked within a certain time frame, a button appears on the page ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Is it possible to utilize the lighten css property within ngStyle in Angular?

Having some trouble with the lighten property in ngStyle and it's not working as expected. I have a color variable within my component that I want to utilize like so: <div [ngStyle]="{color: schedule.group.color, background: 'lighten(' ...

Is there a method to establish varied usage permissions for a single page without any tracking?

I am puzzled by how a solution could create something like this. My goal is to have a webpage displaying 2 squares on a large screen. There will be 2 users, each needing access to write in their own square only on this page. <div class="square1"> ...

Resolving conflicts between TypeGraphQL and Prisma 2 types

Currently, my development stack consists of TypeGraphql, Prisma 2, an Apollo Express server, and a PostgreSQL database. To facilitate the generation of TypeScript types, I utilized Prisma to introspect my database and generate types from the schema.prisma ...

I am unable to access my JavaScript class in Laravel Mix

Within my Laravel project, I have developed a custom form validation class. However, after running npm run dev, I am unable to access this class. Files: small-form-validation.js class SmallFormValidator { errMsgs = { required: 'This fiel ...

Struggling with Angular Components?

Although I have come across discussions on the topic such as this one at How to import component into another root component in Angular 2, my issue remains unresolved. I am facing a similar dilemma. My current challenge involves Angular-Cli - after succe ...

The ng2-chart library displays date in the form of a Unix timestamp

I have a date object imported from my database, but it is showing up as a Unix timestamp (-62101391858000). I know I can format the date using pipes like {{myDate | date:medium}}, however, I am using ng2-charts so I need to find a different solution. My ch ...

Troubleshooting npm test failure on CircleCI due to inability to locate installed package

It's puzzling that Circle is encountering issues with utilizing ts-mocha after it was successfully installed with npm install in a previous step of the build process. The functionality used to function properly, but now it suddenly stopped working. ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...