วันเสาร์ที่ 19 กันยายน พ.ศ. 2563

Installing Angular CLI 10

 

Installing Angular CLI 10

Angular CLI is the official tool for creating Angular projects. Open a new terminal and run the following command to install it:

$ npm install @angular/cli@next --global

At the time of this writing @angular/cli v10.0.0 is installed.

You need to have Node.js installed on your system. On Ubuntu you can follow this tutorial.

Note: You may need to use a CMD line with admin access in Windows or add sudo in Linux and macOS for installing npm packages globally. As of this writing, Angular CLI v10 will be installed.

Creating an Angular 10 Project

After creating the API server, we can now proceed to create our Angular project using Angular CLI 10. In your terminal, navigate to the angular-httpclient-demo folder and run the following command:

$ ng new frontend

The CLI will ask you if you Would you like to add Angular routing? (y/N) Type y and Which stylesheet format would you like to use? (Use arrow keys) Choose CSS and type Enter. Your project should start generating the necessary files and installing the dependencies.

Make sure to read more about the Angular router

Now that we have created the project, before making of HttpClient to send HTTP requests let's first create the basic buildings of our demo application which are simply an HttpService that interfaces with the REST server and a bunch of components for making a CRUD interface that calls the methods of HttpService.

Creating an Angular 10 Service

Let's start with the HttpService. In your terminal, run:

$ cd frontend
$ ng g s http

The command will generate the src/app/http.service.spec.ts (for tests) and src/app/http.service.ts files.

Note: Make sure you have navigated inside the frontend folder before running Angular CLI commands.

Creating Angular 10 Components

Next, let's create four components for displaying (list and by id) and creating/updating the customers:

$ ng g c customer-list
$ ng g c customer-details
$ ng g c customer-create
$ ng g c customer-update

Adding Routing & Navigation

To be able to navigate between these components, we need to add them to the router configuration. Open the src/app/app-routing.module.ts file and update it accordingly:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomerListComponent } from './customer-list/customer-list.component';
import { CustomerDetailsComponent } from './customer-details/customer-details.component';
import { CustomerCreateComponent } from './customer-create/customer-create.component';
import { CustomerUpdateComponent } from './customer-update/customer-update.component';


const routes: Routes = [
  { path:  '', pathMatch:  'full', redirectTo:  'list'},
  { path: 'list', component: CustomerListComponent},
  { path: 'details/:id', component: CustomerDetailsComponent},
  { path: 'create', component: CustomerCreateComponent},
  { path: 'update', component: CustomerUpdateComponent},  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Example of Making HTTP GET Requests using HttpClient in Angular 10

In this section we suppose that we have a component that displays a list of customers from a server.

First let's see the required steps:

  • Import HttpClient from @angular/common/http

  • Inject HttpClient via component constructor

  • Make HTTP GET Requests using .get(endpoint) method

  • Subscribe to the returned observable and show results

Here is the source code of our example:


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

import { Observable } from  "rxjs/Observable";

import { HttpClient } from  "@angular/common/http";



class  Customer {

id : number;

name: string;

email: string;

tel: string;

}



@Component({

selector:  'customers',

template:  `

<ul *ngIf="customersObservable | async as customers else empty">

<li *ngFor="let customer of customers">



</li>

</ul>

<ng-template #empty> No Customers Yet </ng-template>

`})

export  class  CustomerComponent  implements  OnInit {

customersObservable : Observable<Customer[]>;



constructor(private  httpClient:HttpClient) {}



ngOnInit() {

this.customersObservable = this.httpClient

.get<Customer[]>("127.0.0.1:3000/customers")

.do(console.log);

}

}

HTTP GET Request Parameters: HttpParams

In many situations, we need to feed some HTTP parameters to the API endpoint we are querying. In this section we'll see how to use the HttpParams class to use parameters in the HttpClient module.

For instance, let's suppose that we need to make a GET request to this http://127.0.0.1:3000/customers?_page=1&_limit=1 URL for getting the first two customers of the first page.

We start by importing the HttpParams class using:


import {HttpParams} from  "@angular/common/http";

Next, we create an instance of the HttpParams class:


const  params = new  HttpParams().set('_page', "1").set('_limit', "1");

Finally, we call httpClient.get() method with these parameters, then assign the returned Observable to the customersObservable variable:


this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {params});

Using fromString to easily create HttpParams

We can also build HTTP parameters directly from a query string, for example for our previous example URL http://127.0.0.1:3000/customers?_page=1&_limit=1 we can create an instance of HttpParams class from the query string _page=1&_limit=1 by simply using the fromString variable:

const  params = new  HttpParams({fromString:  '_page=1&_limit=1'});

Generic HttpClient request() method

We have previously seen how to use the .get() method to send HTTP GET requests. Now we'll see a generic method to

send GET and the other HTTP methods such as POST, PUT and Delete etc.

Using the .request() method of the HttpClient module we can re-write our previous example to the following code:


const  params = new  HttpParams({fromString:  '_page=1&_limit=1'});



this.customersObservable = this.http.request("GET","http://127.0.0.1:3000/customers",{responseType:"json",params});

Adding custom HTTP Headers to requests

We can also add custom HTTP headers to our HTTP requests using the HttpHeaders class.

First create an instance of the HttpHeaders class and then set your custom HTTP header. For example:


const  headers = new  HttpHeaders().set("X-CustomHttpHeader", "CUSTOM_VALUE");

Next, you can send the GET request using:


this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {headers});

Sending HTTP PUT Requests in Angular 10

The HTTP PUT method is used to completely replace a resource on the API server. We can use the HttpClient module to send a PUT request to an API server using the the put() method. For example:


this.httpClient.put("http://127.0.0.1:3000/customers/1",

{

"name":  "NewCustomer001",

"email":  "newcustomer001@email.com",

"tel":  "0000252525"

})

.subscribe(

data  => {

console.log("PUT Request is successful ", data);

},

error  => {

console.log("Rrror", error);

}

);

Sending HTTP PATCH Requests

The HTTP PATCH method is used to update a resource on the server. The HttpClient class provides the patch() method tha can be used to send UPDATE requests. For example:


this.httpClient.patch("http://127.0.0.1:3000/customers/1",

{

"email":  "newcustomer001@email.com"

}).subscribe(

data  => {

console.log("PUT Request is successful ", data);

},

error  => {

console.log("Error", error);

}

);

Sending HTTP DELETE Requests

Now let's see an example of how we can send an HTTP DELETE request to delete a resource from the API server using delete() method provided by the HttpClient class:

this.httpClient.patch("http://127.0.0.1:3000/customers/1")

.subscribe(

data  => {

console.log("PATCH Request is successful ", data);

},

error  => {

console.log("Error", error);

}

);

Sending HTTP POST Requests in Angular 10

The HTTP POST method has many uses but mostly used when we need to add new data on the server so let's take an example of adding a new customer to our REST API server database using the post() method of the HttpClient class:

this.httpClient.post("http://127.0.0.1:3000/customers",
{
"name":  "Customer004",
"email":  "customer004@email.com",
"tel":  "0000252525"
})
.subscribe(
data  => {
console.log("POST Request is successful ", data);
},
error  => {

console.log("Error", error);

}

);

We are calling the post() method from the injected instance of HttpClient. The first parameter is the API endpoint and the second parameter is the customer data object. We also subscribe to the observable returned by the post() method. If the operation is successful we display POST Request is successful and the data on the console. If there is an error we log the error on the console

วันศุกร์ที่ 11 กันยายน พ.ศ. 2563