I am using Angular 7, and I am trying to use a service that uses HttpClient to call an API link from my APIController in my .Net Core MVC application. Whenever I tried to test in the cmd window after typing in ng test, it gives me an error, and it's only for the service I'm trying to fix:
ProductService should be created
Error: StaticInjectorError(DynamicTestModule)[HttpClient]:
StaticInjectorError(Platform: core)[HttpClient]:
NullInjectorError: No provider for HttpClient!
Here's how I wrote the code in the following files below:
product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Product } from '../product';
@Injectable({
providedIn: 'root'
})
export class ProductService {
productsUrl = "api/ProductsAPI";
constructor(private http: HttpClient) { }
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.productsUrl)
.pipe(
catchError(this.handleError<Product[]>('getProducts'))
);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
//// TODO: better job of transforming error for user consumption
//this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
The product.service file has HttpClient in it, and I read that it doesn't work unless HttpClientModule is in the import section of app.module file, and the product.service class is in the providers section.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ProductsComponent } from './products/products.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { ProductService } from './products/product.service';
@NgModule({
declarations: [
AppComponent,
ProductsComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
AppRoutingModule
],
providers: [ProductService],
bootstrap: [AppComponent]
})
export class AppModule { }
It still gives me a 'No provider for HttpClientModule' error. I want to use the product.service, and import it into another component.
Does anyone have any suggestions or answers on how to remedy this problem?
ng serveorng build? - jcuypers