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 make my code on Google Sheets work across multiple tabs?

My Google Sheets code successfully pulls information from the main tab into my CRM Software every time someone fills out a form online. However, I'm struggling to get the script to run for multiple tabs on the same spreadsheet. I've tried a few s ...

Do not reload the page after a successful ajax request

I'm using an Ajax section to submit data in Laravel. I want the page to not reload if the submission is successful, but to reload if there's an error. Currently, when there is an error, the page reloads correctly. However, I'm facing an issu ...

Tips for preventing double foreach loops in Laravel when dealing with backward relationships

I'm attempting to display variables using the following relationships: First: public function group(){ return $this->belongsTo(Group::class); } Second: public function joinGroups(){ return $this->hasMany(JoinGr ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

The React application is showing an empty page without any visible errors during the compilation process

I'm having trouble with my React app - it compiles without errors but only shows a blank page. Can someone help me figure out what's wrong with my code? I'm new to React and could use some guidance. index.js import React from 'react&ap ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Can the tooltip of an element be changed while the old tooltip is still visible without having to move the mouse away and then back again?

When I have an HTML anchor element with a tooltip that appears when the mouse is hovered over it, and then I use JavaScript to change the tooltip's text using element.title = "Another Tooltip", the new tooltip text does not immediately update visually ...

What is the process for passing an object in the http.send() method?

I'm currently working on sending a POST request to a specific URL using the code below. However, when passing an object to the http.send(params) function, it's resulting in a (400) bad request error. I'm having trouble pinpointing the issue ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

Using Polymer in Chrome Extension content script

Currently, I am experimenting with incorporating Polymer into a chrome extension. My main objective is to take advantage of styling encapsulation in order for my content scripts to operate independently from the CSS on the visited webpage. To begin, I hav ...

Scrolling through a list of objects in a React component to display a vertical lineup of items including the name and logo

Currently, I am working on developing a vertical scrolling ticker/item list that showcases both the name and logo of each item within an array. Initially, I had set up a scrolling ticker solely with names using webkit animations on styled components. Howev ...

How can I utilize Angular and TypeScript to loop through the innerHTML property binding effectively?

I'm currently working on using ngFor to display the binding details of the innerHtml property. <ul> <li *ngFor="let n of NotificationData"> {{n.NotificationID}} <label [innerHtml]="n.NotificationText | StyleHtml&quo ...

Dividing Javascript code in bs4 using Python

I've encountered some challenges when attempting to extract Javascript values from a bs4 code. The javascript snippet appears like this: <script type="text/javascript"> var FancyboxI18nClose = 'Close'; var FancyboxI18nNext = 'Ne ...

Adding flair to the encompassing container

Below is the HTML code that I am working with: <div class="um-field field-date"> <p class="form-row " id="date_field"> <label class="date"> <input data-label="Date" data-value="" type="date" class="input-date um-frontend-f ...

Getting POST data in Next.js is a common task that requires understanding of how the

I am currently working on a form validation project using the App Router within Next.js. // app/register/page.tsx export default function Register(context: any) { console.log("Register page", context.params, context.searchParams); return ...

`At a loss: jQuery failing to retrieve JSON data`

I'm having trouble with a basic script that is supposed to fetch data from a JSON feed and display it in an alert. Despite having loaded jQuery correctly and checked for common issues, the code doesn't seem to be working. I am using jQuery and ca ...

Having trouble with installing Node Windows NPM?

I'm attempting to install a simple package in Node.js, but when I use the standard command, it indicates that it cannot find the file or directory (refer to the image below). Despite updating and re-installing npm, the issue persists. I am using Windo ...

Converting MultiSelect Array from JavaScript to MySQL

I recently implemented a multiselect feature on the client side: <select name="country" data-placeholder="Choose a Country..." tabindex="2"> <option name="country" value="United States">United States</option> & ...

What is the method for defining specific requirements for a generic type's implementation?

I am facing an issue with the following code snippet, where I am trying to restrict the pairing of Chart objects based on correct types for the data and options objects. However, despite my efforts, the TypeScript compiler is not throwing an error in the s ...