Injecting the HttpClient service

The HttpClient service can be injected into our own components and custom classes by leveraging Angular's unique dependency injection system. So, if we ever need to implement HTTP calls, we need to import the HttpClientModule and import the HttpClient service:

// app/biography/biography.module.ts
import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [ HttpClientModule ]
})
export class BiographyModule {}

// app/biography/biography.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/http';

@Component({
selector: 'bio',
template: '<div>{{bio}}</div>'
})
export class BiographyComponent {
bio: string;

constructor(private http: HttpClient) {
const options = {};
this.http.get('/api/bio', { ...options, responseType: 'text' })
.catch(err => Observable.of(err))
.subscribe(x => this.bio= bio)
}
}

In the code provided, we just follow up with the bio example that we pointed out in the previous section. Note how we are importing the HttpClient type and injecting it as a dependency in the Biography constructor.

Usually, we need to perform multiple HTTP calls in different parts of our application, so it's usually recommended to create a DataService and a DataModule that wraps the HttpClientModule and the HttpClient service.

The following is an example of creating such a DataService:

import {Http} from '@angular/http';
import {Injectable} from '@angular/core';

@Injectable()
export class DataService {
constructor(private http:HttpClient) {}

get(url, options?) {}
post(url, payload, options?) {}
put(url, payload, options?) {}
delete(url) {}
}

The corresponding DataModule would look like the following:

import {DataService} from './data.service';
import {HttpModule} from '@angular/http';

@NgModule({
imports: [HttpClientModule],
providers: [DataService]
})

If you want to add your own caching or authorization logic for calling the backend, this is the place to do it. Another way is to use HttpInterceptors, an example of using HttpInterceptors will be provided in an upcoming section in this chapter.

Of course, any module that wanted to use this DataModule would need to import it, like so:

@NgModule({
imports: [DataModule],
declarations: [FeatureComponent]
})
export class FeatureModule {}

And any construct in our FeatureModule can now inject the DataService, like so:

import { Component } from '@angular/core';

@Component({})
export class FeatureComponent {
constructor(private service: DataService) { }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset