17. HttpClient
Install HttpClientModule in AppModule:
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
BrowserAnimationsModule,
ReactiveFormsModule,
FormsModule,
HttpModule,
HttpClientModule,
DashboardModule,
ArchitectureModule,
AppRoutingModule,
SharedModule,
TechnologiesModule,
LoginRoutingModule,
QuestionsModule
]
get() method on HttpClient:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-http-client',
template: `
<h2>My Technologies</h2>
<ul class="list-group">
<li class="list-group-item list-group-item-primary" *ngFor="let result of results">
{{ result }}
</li>
</ul>
`
})
export class HttpClientComponent implements OnInit {
private technologiesURL = 'api/results';
results: string[];
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
//make http request
this.httpClient.get(this.technologiesURL).subscribe(data => {
this.results = data as string[];
});
}
}
Let's view the results in our Chromium Web Browser:
Typechecking the response:
interface ResultsResponse {
results: string[];
}
export class HttpClientComponent implements OnInit {
private technologiesURL = 'api/results';
results: ResultsResponse;
constructor(private httpClient: HttpClient) { }
ngOnInit(): void {
this.httpClient.get<ResultsResponse>(this.technologiesURL).subscribe(data => {
this.results = data;
});
}
}
Reading the full response:
ngOnInit(): void {
this.httpClient.get<any>(this.technologiesURL, { observe: 'response' }).subscribe(resp => {
console.log(resp.headers.get('X-Custom-Header'));
console.log(resp.body);
});
}
Error Handling:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Technology } from './technology';
import 'rxjs/add/operator/retry';
@Component({
selector: 'app-httpclient',
template: `
<h2>My Technologies</h2>
<ul>
<li *ngFor="let technology of technologies">{{ technology.name }}</li>
</ul>
`
})
export class HttpClientComponent implements OnInit {
private technologiesURL = 'api/technologies';
technologies: Technology[] = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get<Technology[]>(this.technologiesURL)
.retry(3)
.subscribe(
results => { this.technologies = results; },
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('there was an error:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
});
}
}
Requesting NON-JSON data:
getTextFile(): void {
this.http.get('/motivation.txt', { responseType: 'text'})
.subscribe(data => console.log(data));
}
POST:
add(name: string): void {
name = name.trim();
if (!name) { return; }
const body = { id: counter++, name: name };
this.technologies.push(body);
this.http.post(this.technologiesURL, body).subscribe();
}
Headers:
add(name: string): void {
name = name.trim();
if (!name) { return; }
const body = { id: counter++, name: name };
this.technologies.push(body);
this.http.post(this.technologiesURL, body, {
headers: new HttpHeaders().set('Authorization', 'my-auth-token')
}).subscribe();
}
URL Parameters:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Technology } from './technology';
import 'rxjs/add/operator/retry';
let counter = 100;
@Component({
selector: 'app-httpclient',
template: `
<h2>My Technologies</h2>
New Technology: <input #box>
<button (click)="add(box.value); box.value = '';">Add</button>
<ul>
<li *ngFor="let technology of technologies">{{ technology.name }}</li>
</ul>
`
})
export class HttpClientComponent implements OnInit {
private technologiesURL = 'api/technologies';
technologies: Technology[] = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get<Technology[]>(this.technologiesURL)
.retry(3)
.subscribe(
results => { this.technologies = results; },
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('there was an error:', err.error.message);
} else {
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
});
}
add(name: string): void {
name = name.trim();
if (!name) { return; }
const body = { name: name };
this.http.post(this.technologiesURL, body, {
params: new HttpParams().set('id', counter++ + '1')
}).subscribe(technologies => this.technologies.push(technologies as Technology));
}
getTextFile(): void {
this.http.get('/motivation.txt', { responseType: 'text'})
.subscribe(data => console.log(data));
}
}
Interceptor:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request);
}
}
Provide for Interceptor:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { TechnologiesComponent } from './technologies.component';
import { TechnologyDetailComponent } from './technology-detail.component';
import { DashboardComponent } from './dashboard.component';
import { TechnologySearchComponent } from './technology-search.component';
import { HttpClientComponent } from './httpclient.component';
import { TechnologyService } from './technology.service';
import { TechnologySearchService } from './technology-search.service';
import { NoopInterceptor } from './noop-interceptor.service';
@NgModule({
declarations: [
AppComponent,
TechnologiesComponent,
TechnologyDetailComponent,
DashboardComponent,
TechnologySearchComponent,
HttpClientComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
HttpClientModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true
},
TechnologyService,
TechnologySearchService
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Mutate Request:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const duplicateRequest = request.clone();
const secureRequest = request.clone({url: request.url.replace('http://', 'https://')});
return next.handle(secureRequest);
}
}