Submodule 22.3: Angular HTTP Client - Practice
Site: | ΕΛ/ΛΑΚ Moodle |
Course: | Study / Web Design and Web Development |
Book: | Submodule 22.3: Angular HTTP Client - Practice |
Printed by: | Guest user |
Date: | Thursday, 21 November 2024, 5:14 PM |
Introduction
In this submodule, you will learn to use the Angular HTTP client to make requests for data to a server and obtain and process the response. You will :
- Use Angular HTTP client to obtain data from a server
- Process the HTTP response from the server to retrieve the data and use it in your application.
We'll see how we can leverage the HTTP client which will return an observable to us. We have already reconfigured our application especially the service to be able to deliver observables to our components. And within our components, we are subscribing to these observables. So the major part of the setup for obtaining data from the service to the component is already there.
Starting with the HttpClientModule
You need to import the HttpClientModule
in app.module.ts
by adding the following to the file:
...
import { HttpClientModule } from '@angular/common/http';
...
@NgModule({
...
imports: [
... ,
HttpClientModule
],
...
Having imported HttpClientModule into the AppModule, you can inject the HttpClient into an application class as shown in the "Updating the Dish service" page.
Configuring the Base Server URL
Create a new file named baseurl.ts
in the shared folder and update its contents as follows:
export const baseURL = 'http://localhost:3000/';
Note the export of the constant named baseURL
which is set to http://localhost:3000
. Recall that this is the base URL at which the JSON server is accessible.
Import baseURL
and update the AppModule's providers property of the @NgModule
decorator as follows:
...
import { baseURL } from './shared/baseurl';
...
@NgModule({
...
providers: [...
LeaderService,
{provide: 'BaseURL', useValue: baseURL}],
...
Angular provides a way of supplying values to the rest of the application by configuring a provider within your app module.
Note the import of { baseURL } from './shared/baseurl';
This value can now be made available to the rest of the application by going to the providers and adding {provide: 'BaseURL', useValue: baseURL}],
.
Updating the Dish Service
Open dish.service.ts
file and update its contents as follows:
...
import { HttpClient } from '@angular/common/http';
import { baseURL } from '../shared/baseurl';
import { Dish } from '../shared/dish';
@Injectable()
export class DishService {
constructor(private http: HttpClient) { }
getDishes(): Observable<Dish[]> {
return this.http.get<Dish[]>(baseURL + 'dishes');
}
getDish(id: number): Observable<Dish> {
return this.http.get<Dish>(baseURL + 'dishes/' + id);
}
}
Note the injection of the HttpClient into the class DishService
DishService requests JSON data from the server and fetches these with a get() method on HttpClient, this.http.get<Dish[]>().
HttpClient.get
constructs an Observable
with configured GET request and when the Observable instance is subscribed, GET request is executed on the server.
Updating Menu Component
Open menu.component.ts
and update it as follows:
import { Component, OnInit, Inject } from '@angular/core';
...
constructor(private dishService: DishService,
@Inject('BaseURL') public BaseURL) { }
...
MenuComponent, injects the DishService and calls the getDishes() service method.
Open menu.component.html
and update it as follows:
src="{{BaseURL + dish.image}}"
Now the reason why we injected the BaseURL within the component is that, in the template, we are obtaining the dish.image . This dish.image needs to be obtained from the json-server. So, we need to update the source to be BaseURL + dish.image. In order for this to work correctly, we need to enclose the src within quotes.
Updating Dishdetail Component
Open dishdetail.component.ts
and update it as follows:
import { Component, OnInit, Inject } from '@angular/core';
...
constructor(private dishService: DishService,
@Inject('BaseURL') public BaseURL) { }
...
DishdetailComponent, injects the DishService and calls the getDish() service method.
Open dishdetail.component.html
and update it as follows:
src="{{BaseURL + dish.image}}"
The results
With the previous code configured, open your Terminal, go to the jsonServer
sub-folder and run json-server --watch db.json -d 2000
. This will introduce a delay of 2 seconds before the server sends the reply for the request. The server will serve the db.json file for your application. You can watch the server in your browser URL localhost:3000
Open another Terminal window, go to the angularChocoYourname
angular-sub-folder and run ng serve
to run your application in development mode. In your browser navigate to the URL localhost:4200
The menu page has been server by the json-server. If you stop the server, there is not content available to the page. In contrast, the about page takes the data by the application, so this is not affected by the server.
In the next assignment, you will enable the server to serve the about page.
Do a Git commit with the message "Angular HttpClient".