Creating service for the HttpClient
Since most HTTP requests are completely independent of components, it is recommended that you bind them to a separate service. In this way, your service can be mocked and your application becomes more testable.
Let’s create a new service. To create a new service, we can use angular-cli. To create a service, open the command prompt and run the following code to create a service:
Ng generate service DemoService
After running this command, there will be two files created: demo-service.service.ts and demo-service.service.spec.ts
The basic service file Demo-service.service.ts look like this:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DemoServiceService {
constructor() { }
}
To make an HTTP request from our service, we need the Angular HttpClient. We can request this client easily by adding dependencies.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class DemoServiceService {
constructor( private httpClient: HttpClient ) { }
}