Creating a simple HTTP Request in Angular
Maybe you’re using Angular as the frontend to a Drupal site, or you are integrating it into a .NET build. No matter the use case of Angular, you will most likely need to create an HTTP request at some point. The first step, is to create a service. I prefer to use the Angular CLI for all file generation. Simply run this in your project to generate a requests service.
ng generate service requests
Inside out newly created service, we will need to import a few things before we can start – it should be noted this is based on Angular 6.
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs/Rx';
import { map } from 'rxjs/operators';
import { HttpClient HttpHeaders } from '@angular/common/http';
A couple of notes on the imports, we import the environment, so that we can easily switch between endpoints for a development and production environment, rather than having to manually change it before deploying the build. We also import map rather than all of rxjs, to keep down the weight of our build.
The rest of our service will look something like this:
export class RegistrationService {
private endpoint = environment.APIEndpoint;
constructor(public http: HttpClient) { }
// Pre registration Request - checks Contractor ID and Phone before letting user proceed with the form
public preRegister(req) {
let reqBody = JSON.parse(req);
let httpHeaders = new HttpHeaders({'Content-Type': 'application/json',});
return this.http.post(this.endpoint + '/preregister', reqBody, { headers: httpHeaders })
.pipe(map((response: Response) => {return response;})
);}
A little bit about each part of our request
- Endpoint, this is the path to our API, and will change from dev to prod if necessary. It is set in our environment config files.
- reqBody, this is the body of our request, that is passed in when we use the service.
- httpHeaders, in this case we are just setting the Content-Type, but you could also pass auth tokens this way.
Once it’s all setup we can simply import our service in the necessary file, inject it in that files constructor and use like this:
this.requestService.preRegister().subscribe((data)=>{
//manipulate the response here.
console.log(data);
})