How to deal with HTTP requests in Angular 7/8?

In this tutorial, I will show you how to deal with Http requests in Angular 8. So in the next sections, I will talk about two HTTP methods: GET and POST. (It’s the same process for the other HTTP requests)

GET HTTP request

Get HTTP Request allows you to fetch data from your back-end server. For this quick example, let’s fetch user data from the route ‘/users/<id>’:

class User {
  firstName: string;
  lastName: string;
  birthday: string;
  genre: 'Male' | 'Female';
  address: string;
}

user.ts

The user object is like a contract between the client and the server. It means ‘Hi server, I want to get a user and here is the data I’m expecting’. Then here is how you fetch user data:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from  '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule // Add this line
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.module.ts

First, add the HttpClientModule to the app.module.ts. Then create the UserService like this:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UserService {

  constructor(private httpClient: HttpClient) {}

  getUser(id: number): Observable<User> {
    return this.httpClient.get<User>(`/users/${id}`);
  }
}

user.service.ts

In this service, we inject HttpClient, then we create the getUser function. This function returns a user Observable by calling the get method of httpClient. Notice that in this example, I also show you how to use path parameter in angular. So, once it’s done, you can call the service by doing this:

import {Component, OnInit} from '@angular/core';
import {UserService} from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
  }

  getUser(id: number) {
    this.userService
      .getUser(id)
      .subscribe((user) => {
        console.log(user);
      });
  }

}

app.component.ts

The getUser function is an Observable we need to subscribe to trigger the call. And finally, here is the HTML code to call the getUser function:

<button (click)="getUser(1)">Get User 1</button>

app.component.html

The click on this button triggers http://localhost:4200/users/1.

In the last example, I show you how to use path parameter. Now let’s see for query parameters. To do this, let’s assume that we want to get a list of users by filtering on some fields:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UserService {

  constructor(private httpClient: HttpClient) {}

  searchUser(firstName: string, genre: 'Male'|'Female'): Observable<User[]> {
    return this.httpClient.get<User[]>('/users', {
      params: {firstName, genre}
    });
  }
}

user.service.ts

import {Component, OnInit} from '@angular/core';
import {UserService} from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
  }

  searchUser(firstName: string, genre: 'Male'|'Female') {
    this.userService
      .searchUser(firstName, genre)
      .subscribe((users) => {
        console.log(users);
      });
  }

}

app.component.ts

This request will trigger this http call: http://localhost:4200/users?firstName=Paul&genre=Male

To use query parameters, we just need to use the ‘params’ attribute. Actually, it’s the same thing for all other Http requests. Let’s see how to post data with a body in Angular.

POST HTTP Request

In this section, I will show you how to post data with a body. Let’s assume we want to register a new user. To do this, we need to send a user object to our server by using a POST http request on the route ‘/users’. Here is how we can achieve this:

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UserService {

  constructor(private httpClient: HttpClient) {}

  registerUser(user: User): Observable<User> {
    return this.httpClient.post<User>('/users', user, {
      params: {
        role: 'CUSTOMER'
      }
    });
  }
}

user.service.ts

Here, we can see that the second parameter is the body. For a full example I added the params attribute.

import {Component, OnInit} from '@angular/core';
import {UserService} from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
  }

  registerUser(user: User) {
    this.userService
      .registerUser(user)
      .subscribe((userSaved) => {
        console.log(userSaved + ' saved');
      });
  }

}

app.component.ts

<button (click)="registerUser({
firstName: 'Paul',
  lastName: 'James',
  birthday: '05/01/1992',
  genre: 'Male',
  address: 'New York'
})">Create User</button>

app.component.html

When we call the registerUser function, the HTTP call is: ‘http://localhost:4200/users?role=CUSTOMER’ with this payload:

{
"firstName":"Paul",
"lastName":"James",
"birthday":"05/01/1992",
"genre":"Male",
"address":"New York"
}

Conclusion

  • Angular Http request returns Observables
  • Use the ‘params’ attribute to add query parameters
  • For path parameters use the typeScript replacement method
  • The second parameter of post method is the body

Be the first to comment

Leave a Reply

Your email address will not be published.


*