Angular is a popular front-end framework made by Google. Like other popular front-end frameworks, it uses a component-based architecture to structure apps.
In this article, we’ll look at how to configure the Angular HTTP client to make requests that we want to make.
URL Query Strings
We can use the HttpParams
class to add URL query strings to our HtttpRequest
.
For example, we can write the following code to get a response from the Unsplash API:
app.module.ts
:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { AppComponent } from "./app.component";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
:
import { Component } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css]
})
export class AppComponent {
constructor(private http: HttpClient) {}
ngOnInit() {
this.getPhotos();
}
getPhotos() {
const options = {
params: new HttpParams()
.set("page", "1")
.set(
"client_id",
"your_unsplash_api_key"
)
.set("query", "photo")
};
this.http
.get("https://api.unsplash.com/search/photos", options)
.subscribe(res => console.log(res));
}
}
In the code above, we created a new HttpParams
object and call the set
method on the instance to add a new query string parameters.
Then we make the GET request with the get
method with the options
object passed into it, which sets the query string.
Use fromString
to Create HttpParams
We can also create the query for theHttpParams
from a string.
To do this, we can write the following:
app.component.ts
:
import { Component } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(private http: HttpClient) {}
ngOnInit() {
this.getPhotos();
}
getPhotos() {
const options = {
params: new HttpParams({
fromString:
"page=1&client_id=your_unsplash_api_key&query=photo"
})
};
this.http
.get("https://api.unsplash.com/search/photos", options)
.subscribe(res => console.log(res));
}
}
In the code above, we passed in the whole query string as the value of the fromString
property.
Debouncing Requests
We can use the Rxjs debouceTime
operator to delay the request by the amount of time that we specify.
For example, we can write:
app.component.ts
:
import { Component } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
import { debounceTime, distinctUntilChanged } from "rxjs/operators";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(private http: HttpClient) {}
ngOnInit() {
this.getPhotos();
}
getPhotos() {
const options = {
params: new HttpParams({
fromString:
"page=1&client_id=your_unsplash_api_key&query=photo"
})
};
this.http
.get("https://api.unsplash.com/search/photos", options)
.pipe(
debounceTime(500),
distinctUntilChanged()
)
.subscribe(res => console.log(res));
}
}
In the code above, we use the pipe
method to apply the debounceTime
operator to delay the request by 500 milliseconds.
Then we emit the value from the get
observable when it’s changed by using the distinctUntilChanged
operator.
Listening to Progress Events
We can listen to the progress of the request by setting the reportProgress
option to true
.
For example, we can listen to progress events as follows:
app.component.ts
:
import { Component } from "@angular/core";
import { HttpClient, HttpParams, HttpRequest } from "@angular/common/http";
import {
debounceTime,
distinctUntilChanged,
last,
tap,
map
} from "rxjs/operators";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(private http: HttpClient) {} ngOnInit() {
this.getPhotos();
}
getPhotos() {
const options = {
params: new HttpParams({
fromString:
"page=1&client_id=your_unsplash_api_key&query=photo"
}),
reportProgress: true
};
const req = new HttpRequest(
"GET",
"https://api.unsplash.com/search/photos",
{},
options
);
this.http
.request(req)
.pipe(
map(event => console.log(event)),
tap(message => console.log(message)),
last()
)
.subscribe(res => console.log(res));
}
}
In the code above, we call the request
method to make the request.
The method takes an HttpRequest
object, which takes the HTTP request method as the first argument, the second is the URL, the 3rd is the payload, the 4th is the options.
We add the reportProgress
into the options object.
Then to get the progress, we use the tap
operator to log the progress.
We get something like:
{type: 3, loaded: 65536, total: 72147}
where loaded
is the number of bytes loaded. The total
is the total number of bytes loaded.
Security: XSRF Protection
Cross-site request forgery (XSRF) is an attack where attackers trick an authenticated user into unknowingly run actions on a website.
HttpClient
has built-in XSRF protection mechanisms to prevent these attacks.
It sets the X-XSRF-TOKEN
in the request headers with the XSRF token.
A server-side app can verify that the XSRF token is correct so that attackers can’t make a request by masquerading as a legitimate user.
Configuring Custom XSRF Cookie/Header Names
We can change the XSRF cookie or header name. by adding the HttpClientXsrfModule.withOptions()
to the imports
array of our app’s NgModule
.
For example, we can write:
app.module.ts
:
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule, HttpClientXsrfModule } from "@angular/common/http";
import { AppComponent } from "./app.component";
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: "My-Xsrf-Cookie",
headerName: "My-Xsrf-Header"
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
In the code above, we changed the key of the XSRF cookie to My-Xsrf-Cookie
and the key of the XSRF header to My-Xsrf-Header
.
Conclusion
We can use the HttpParams
object to set the query string of our requests.
To debounce requests, we can use the debounceTime
operator to delay requests.
With Angular’s HTTP client, we can also listen to the progress of our request by setting the reportProgress
option to true
.
Angular’s HTTP client has XSRF protection built-in to secure the requests.