The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClient is added to the constructor. Surprisingly, everything works perfectly fine when HttpClient is omitted from the setup. Can anyone guide me on how to successfully retrieve information from CSV files without disrupting the functionality of the webpage? My sincere apologies for any confusion caused. Below is the code snippet for ConnexionService:

import { Injectable } from '@angular/core';
import { Auth, User, authState, signOut, signInWithPopup, GoogleAuthProvider } from '@angular/fire/auth';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ConnexionService {

    constructor(private fbAuth: Auth, private http : HttpClient) { } 
    readonly obsUser: Observable<User | null> = authState(this.fbAuth);
    
    async logout(): Promise<void> {
     return signOut(this.fbAuth);  
        } 
    
    async loginGoogle(): Promise<void> {   
          return signInWithPopup(this.fbAuth, new GoogleAuthProvider()).then( 
            (result) => {
              const credential = GoogleAuthProvider.credentialFromResult(result);
             let token: string | undefined;
  
             if (credential) {
              token = credential.accessToken;
              } else { 
                 console.error("La credential est null.");
  }
              const user = result.user;
            }).catch((error) => {
              const errorCode = error.code;
              const errorMessage = error.message;
              const email = error.customData.email;
              const credential = GoogleAuthProvider.credentialFromError(error);
            }
      
        )       
      } 
        
        lireLivreur(csvData:string){
          const lines=csvData.split('\n');
          const result:Livreur[]= [];
      
          const headers=lines[0].split(',');
          for(let i=1;i<lines.length;i++){
            const obj: ParsedData = {};
            const currentLine=lines[i].split(',');
            for(let j=0;j<headers.length;j++){
              obj[headers[j]]=currentLine[j];
            }
            const livreur:Livreur={
              trigramme:obj[headers[0]],
              prenom:obj[headers[1]],
              nom:obj[headers[2]],
              photo:obj[headers[3]],
              telephone:obj[headers[4]],
              emploi:obj[headers[5]],
              entrepot:obj[headers[6]],
              tournees:obj[headers[7]],
            }
            if(livreur.emploi=='livreur'){
              result.push(livreur);
            }     
          }
          return result;
        }
        
        lireInfos(){
          this.http.get('./assets/Export_Employés.csv',{responseType:'text'})
          .subscribe(data=>{
            this.livreurs=this.lireLivreur(data);
          },
        );
      }
      
        livreurs : Livreur[]=[];
         livreur: Livreur = {
          trigramme: '',
          prenom: '',
          nom: '',
          photo: '',
          telephone: '',
          emploi: '',
          entrepot: '',
          tournees: ''
        };   
    }

interface Livreur {
  trigramme: string;
  prenom: string;
  nom: string;
  photo: string;
  telephone: string;
  emploi: string;
  entrepot: string;
  tournees: string;
}    

interface ParsedData {
  [key: string]: string;
}

Below is the code snippet for ConnexionComponent:


changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ConnexionComponent {
    constructor(private cox: ConnexionService){
    }

    
    async logGoogle():Promise<void>{
        this.cox.loginGoogle();
    }
    
    async logOut():Promise<void>{
        this.cox.logout();
    }
  }

It's strange that even before injecting my Connexion service into my component, it already faces issues. This leads me to believe that there might be a problem within the ConnexionService itself.

Answer №1

Have you included the HttpClientModule in your Angular application?

There are two methods to achieve this. If you are using the standalone version of the Angular application, make sure to provide the HttpClient by using the provideHttpClient function in your main.ts.

Standalone Angular:

main.ts
bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient()
  ]
}) 

If your application is built with modules, remember to import the HttpClientModule in your AppModule.

Using Modules:

app.module.ts
@NgModule({
  imports: [
    HttpClientModule,
  ],
  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

Is there a way to incorporate an 'input' type within an Icon Button component from Material UI in a React project?

Kindly review my code below. I have revamped it for clarity so you won't need to stress about important details! const test = () => { return ( <label > <input type='file' multiple style={{ display: &ap ...

Showing records from Firebase that are still within the date range

I'm currently developing an application that allows users to book appointments on specific dates. After booking, I want the user to only be able to view appointments that are scheduled for future dates. I've attempted to compare the date of each ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Discover the latest techniques for incorporating dynamic datalist options in Angular 13 with Bootstrap 5

React 17 Tailwind CSS dynamiclist.component.html <div> <label for="{{ id }}" class="form-label">{{ label }}</label> <input class="form-control" list="{{ dynamicListOptions }}" [i ...

Unique ways to serialize an HTML element efficiently: JavaScript tricks

Is there a way to store a reference of an HTML tag for future use? For instance, if I click on a div and save a pointer to that div in JavaScript, is it possible to serialize this pointer and then de-serialize it to use in another part of the web applicat ...

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Learn how to stream videos using the YouTube Player API's loadPlaylist feature

Is there a way to make the next video play automatically using the loadPlaylist option? I've tried implementing this code but unfortunately, it doesn't work and the video won't play: <div id="player"></div> <script> var ...

Having difficulty populating a table with JSON data in Angular without encountering any error messages

After executing a query on my database, I realized that although the JSON data is correct (as confirmed through the console), the table does not populate as expected. Here is the code snippet for my component: @Component({ selector: 'app-envios&apo ...

Customize the position of the Datetimepicker

Is there a way to customize the position of the datetimepicker, ensuring that it stays within the visual boundaries without getting cut off? I need help with this. ...

Struggling to generate a fresh invoice in my project using React.js

I am fairly new to working with React and could really benefit from some assistance in understanding how to implement a new invoice feature within my current project. The Challenge: At present, I can easily create a new invoice as showcased in the images ...

Tips for optimizing search functionality in Angular to prevent loading all data at once

An exploration for information within vast datasets is triggered by AngularJS when the input contains more than 3 characters. var app = angular.module('test_table', []); app.controller('main_control',function($scope, $http){ $scope ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Tips for transferring the output of a JavaScript async function to a Python variable

var = driver.execute_script("setTimeout(function(){ return [1,2,3]; }, 1000);") Utilizing the Selenium method execute_script, I am attempting to extract data from a website using javascript and assign it to a python variable var. The challenge a ...

Tips for aligning the types of objects transmitted from a Web API backend to a React/Redux frontend

After creating a backend for my app using .net, I now have CRUD operations available to me. When performing a POST action, the response includes an entire new item object: {"Id":"7575c661-a40b-4161-b535-bd332edccc71","Text":"as","CreatedAt":"2018-09-13T15 ...

What initiates Electron after npm processes the package.json file?

As I delve into the realms of JavaScript, HTML, and Electron, a particular question has been playing on my mind - what exactly happens when you run electron . in the "scripts" -> "start" section of package.json? The mysterious way it operates sends shivers ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Challenges with ExpressJS 4 middleware

Trying to grasp the concept of middleware in ExpressJS 4 has been quite a challenge for me. As far as I understand, middleware are applied based on the order they are declared and can be "bound" at different levels. My current focus is on binding a middl ...