Search code examples
angularangular-httpclient

StaticInjectorError


This is my HttpClient code:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CreeperUser } from '../Models/CreeperUser';
import { Observable } from 'rxjs';

@Component({
    templateUrl: 'friends.component.html'
})
export class FriendsComponent {
    users: number;

    constructor(private http: HttpClient) {
        this.DisplayUser();
    } 

    public CallApi_HttpGet(): Observable<CreeperUser[]> {
        return this.http.get<CreeperUser[]> ('https://localhost:44399/api/user');
    }

    public DisplayUser(){
        this.CallApi_HttpGet().subscribe(response => {
            this.users = response[0].userId;
        });
    }
}

And when I run the code, the Chrome's console told me this:

Error: Uncaught (in promise): Error: StaticInjectorError(AppModule) 

enter image description here


Solution

  • You have not provided providers in your module;

     import { HttpClientModule, HttpClient } from '@angular/common/http';
    .
    .
    .
    @NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        BrowserAnimationsModule,
        FormsModule,
        AppRoutingModule
    ],
    providers: [ HttpClientModule, ... ]
    

    Hope this will solve your problem