Published
- 2 min read
Webservice with Angular 17
// dummy.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Product } from './product';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DummyService {
constructor(private http: HttpClient) { }
public getProducts(): Observable<Array<Product>> {
const endpoint =
'https://hub.dummyapis.com/products?noofRecords=5&idStarts=1001¤cy=usd';
return this.http.get<Array<Product>>(endpoint);
}
}
// product.ts
export interface Product {
id: number;
description: string;
name: string;
price: number;
}
It’s important to provide the HttpClient in your Angular 17 configuration. If you forget this step you will get something like this:
ERROR NullInjectorError: R3InjectorError(Standalone[_ProductsListComponent])[_DummyService -> _DummyService -> _DummyService -> _HttpClient -> _HttpClient]: NullInjectorError: No provider for _HttpClient!
// app.config.ts
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideRouter(
routes) // withDebugTracing()
]
};
// main.ts
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));
or if you use the module based approach:
// app.module.ts
import { HttpClientModule } from '@angular/common/http';
// app.module.ts
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
...
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
public constructor(viewportService: ViewportService) {
viewportService.attach();
}
}
And this is how you use it:
// just-a.component.ts
constructor(private dummyService: DummyService) {
this.dummyService.getProducts().subscribe((resp: Array<Product>) => {
console.log(resp);
});
}