Experiencing challenges with modernizing a legacy Angular project, switch from using the old HTTP module to the new HTTP

In an Angular 7 project I am working on, there is some code that was written around 5-6 years ago. I am currently in the process of updating the application to the latest version of Angular. My focus right now is on testing the login functionality of the app which uses basic HTTP authentication. Refactoring this part of the code is the final step before upgrading the entire UI from Angular 7 to 14.

Below is the old code snippet:

import { ConnectionBackend, Http, Request, RequestOptions, RequestOptionsArgs, Response, XHRBackend } from '@angular/http';
import { AuthService } from './../auth/auth.service';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class AuthHttp extends Http {
    constructor(backend: XHRBackend, defaultOptions: RequestOptions, private auth : AuthService) {
        super(backend, defaultOptions);
        this.auth = auth;
    }
    // Other methods and operations go here...
}

I have attempted various approaches to refactor the code but haven't made much progress. As a first-time Angular user, navigating through this moderately sized project has been challenging. While searching for solutions, I haven't come across anyone tackling a similar issue.

The compilation does not throw any errors when using an empty class as shown below. The imports seem to be equivalent or close to it for the new HttpClient module in Angular.

import { AuthService } from './../auth/auth.service';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpParams, HttpHeaders, HttpXhrBackend, HttpResponse, HttpBackend, HttpRequest, HttpEvent } from '@angular/common/http';
@Injectable()
export class AuthHttp extends HttpClient {}

However, upon running ng serve with the blank class above, I encounter two errors in the browser console:

ERROR NullInjectorError: R3InjectorError(AppModule)[ApiService -> ApiService -> ApiService]: 
  NullInjectorError: No provider for ApiService!
    Angular 9
    AppComponent_Factory app.component.ts:11
    Angular 26
    631 main.ts:11
    Webpack 7
core.mjs:6362:22
    Angular 16

Any guidance on how to proceed or useful resources would be greatly appreciated. Thank you.

This is the implementation of the ApiService:

@Injectable()
export class ApiService {
  // Methods and operations within the service go here...
}

Answer №1

It's tough to pinpoint the problem without inspecting the implementation of ApiService itself. Overall, it appears that there might be an issue with how the ApiService is being supplied from a module.

A simple solution could involve providing it at the root level of the application. @Injectable({ providedIn: 'root', }) export class ApiService ....

Answer №2

After some troubleshooting, I was able to get it functioning. However, I still have some uncertainties regarding how it operates and its purpose. The previous method seemed convoluted due to the restrictions of older versions of Angular 2.

@Injectable()
export class AuthHttp extends HttpClient implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const authReq = req.clone({
            withCredentials: true
        });
        return next.handle(authReq);
    }
}

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

Ways to transform a string into a mongodb ObjectId

I have successfully inserted the following in MongoDB as a string. However, I would like it to be inserted as an objectId. parentId": "5ced2388dbbbe124d8671067" This is the parentId stored in string format. Is there a way to convert it to objectId forma ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

Two distinct approaches for user interface and application programming interface

Here's a non-technical question that's been on my mind lately. I've noticed that developers often create separate projects for their Angular applications using Visual Studio Code, and separate projects for their .NET Core Web API applicatio ...

Having issues with uploading a webcam picture using ajax. Occasionally the image only seems to be saved partially. Any suggestions on what I might be

Working on my web application involves taking customer photos and uploading them with Ajax. I base64 encode the pictures, resulting in large data sizes (around 1.4MB). The process involves Ajax calling a php script to handle the data transfer and saving it ...

The type 'Readonly<Ref<Readonly<any>>>' does not have the property 'forEach' available

Having an issue with state management in Vue3 (Pinia) using the Composition API. I successfully retrieved an array called countryCodes and now I want to copy all items from this array into another array called countries defined in the state. However, whe ...

In Javascript, the splice method removes all elements except the specified element

I've got a straightforward script here that grabs content from an input box, converts it into an array, deletes a specific element, and then displays the remaining text. My issue is with using "splice()" to remove the item as it's deleting every ...

Is it possible to incorporate custom meta tags into next.js 13 using static metadata objects?

I'm trying to block Pinterest on my website by adding the meta tag <meta name="pinterest" content="nopin" /> in the site's header, but I'm uncertain how to do this in Next 13 using the new exported metadata object f ...

Issue encountered with TinyMCE integration in Angular 2

As a newcomer to Angular 2, I recently attempted to integrate the TinyMCE editor into my project. I diligently followed the instructions outlined in this guide to create and implement the TinyMCE component: Despite meticulously following each step, I enc ...

Please ensure that the subscription data is fully loaded before utilizing it as input

Recently, I have been developing a service that retrieves a list of users to be used as input for a child component. However, I encountered an issue where the component loads before the users list is fully loaded. One solution I came up with is to implemen ...

What is the best way to execute a JavaScript method in a server-side button control?

function calculateRoute() { var startLocation = document.getElementById('start').value; var endLocation = document.getElementById('end').value; var requestParams = { origin: startLocation, ...

Troubleshooting problem with reloading in Angular 2 Electron application

I have been developing an Electron desktop app using Angular 2. Everything is working perfectly when the application boots up, but I face issues when trying to reload it. It seems like there is a problem with the routing. When there is no routing involved ...

Utilize Vue3 to categorize items and showcase the quantities from the product list

I successfully counted every repeated element in my array, now I just need to display only one of each product along with its quantity. Here is the current progress: https://i.sstatic.net/SBm64.png I have a function that I'm exporting from a file n ...

Retrieve information from various tables in a SQLite database using Node.js

Is there a method to retrieve all data from multiple tables in a database? Currently, I have managed to fetch all data from a single table: router.get('/', function (req, res, next) { db.serialize(function () { db.all('SELECT id, name ...

Exploring the population with embedded RxJs queries

I'm struggling to find a solution to this particular issue. Imagine there is an object type described as follows: Box { Fruit[n]: { Kinds[n]: { id: string; name: string; } } } From an API call, I received a bo ...

Performing aggregation in MongoDB to calculate the sum total

I'm trying to figure out how to calculate a sum based on a specific row in the mongo aggregation module. Here is the structure of my document: { "_id" : "315" "city" : "Dallas", "population" : 3400, "state" : "Unknown" } How c ...

Exploring unit testing strategies for a Vue component with a namespaced store and mocking Vuex

Currently, I am working on creating a login component with vue, vuex, and vuetify. To implement this, I opted for using a namespaced auth module in the store; however, I encountered an issue along the way. I have adopted a Test-Driven Development (TDD) ap ...

Explaining the union type using a list of data types

Is there a way to create a union type that strictly limits values to 'a', 'b', 'c' when using a list like const list: string[] = ['a', 'b', 'c']? I know one method is: const list = ['a' ...

Tips for organizing JSON information in ReactJS

Could someone lend a hand with sorting JSON data in ReactJs? I'm having trouble getting it to work properly. Also, if I want to sort by title, would it be the same process? Thanks! This is what I've tried so far: componentDidMount() { ...

The JSON file is not being parsed by Javascript

Attempting to create an HTML-based player that requires a playlist to function. Encountering issues with reading a local JSON file on Chromium running on Raspberry Pi 3, although the entire setup works flawlessly on my laptop using EDGE (the getJSON functi ...

Angular Material SnackBar not responding to the `onAction()` method

I'm encountering an issue with the Angular Material SnackBar's onAction() method. It seems that it is not triggering after the button is clicked. Even though I have subscribed to the onAction, afterDismissed, and afterOpened methods, only the lat ...