The previous post, we had introduced Angular Components (Angular4 Component). And in the tutorial, JavaSampleApproach will continuously show you how to use Angular Services (Angular4 Services) to develop an Angular Application.
Related articles:
– How to setup Angular IDE with Spring Tool Suite
– Create a new Angular4 Component – Multiple Components Angular Application
I. Technologies
– Angular 11
– SpringToolSuite: Version: 3.8.0.RELEASE
II. Angular Service
What is Angular Service?
Angular Service is an JavaScript function that’s responsible for doing a specific task. Using Services to exchange and processing data then keeps Components focused on doing business logic on the view. So it’s very helpful to organize a big project that makes codes more clear and clean for development and reusability.
III. Practice
Step to do:
– Create an Angular Service
– Implement logic for Angular Application
– Run and check results
***Note: to do the tutorial, We reuse the sourcecode and continue with the previous post. So please check out it for more details:
– Create a new Angular4 Component – Multiple Components Angular Application
1. Create an Angular Service
Right click on /angular4client/src/app, choose: File -> New -> Service:
Press Finish,
-> New project’s structure:
Log: “WARNING Service is generated but not provided, it must be provided to be used”
-> Need register the DataService by using providers property. So we will do it later in a below session.
We got 2 new files: data.service.spec.ts and data.service.ts. Check sourcecode of the main file data.service.ts:
import { Injectable } from '@angular/core'; @Injectable() export class DataService { constructor() { } }
2. Implement Logic for Angular Application
2.1 Create a Customers Mock Data
– Right click on folder /angular4client/src/app, choose File ->
import { Customer } from './Customer'; export const CUSTOMERS: Customer[] = [ {id: 1, firstname: 'Mary', lastname: 'Taylor', age: 24}, {id: 2, firstname: 'Peter', lastname: 'Smith', age: 18}, {id: 3, firstname: 'Lauren', lastname: 'Taylor', age: 31} ];
2.2 Implement DataService
– Modify DataService as below:
import { Injectable } from '@angular/core'; import { Customer } from './customer'; import { CUSTOMERS } from './mock-customers'; @Injectable() export class DataService { constructor() { } getCustomers(): Promise{ return Promise.resolve(CUSTOMERS); } }
A Promise is used to make the DataService to be an Async services that supports a call back when the processing is done.
2.3 Inject DataService and re-implement AppComponent
To use DataService, AppComponent must inject it:
... import { DataService } from './data.service'; export class AppComponent implements OnInit { ... constructor(private dataService: DataService) {} ...
Is it Done?
-> NO, an exception will be thrown out when running:
... EXCEPTION: No provider for DataService! (AppComponent -> DataService) ...
Why?
-> The reason comes from the above WARNING Log. For resolving it, We need register DataService by using provider property. And having 2 approaches for doing it:
– Add DataService on providers array property of AppModule in app.module.ts file.
... import { DataService } from './data.service'; @NgModule({ ... providers: [DataService], bootstrap: [AppComponent] }) export class AppModule { }
With the approach, DataService will be ready to use at all Components of the Angular Application.
– Add providers: [DataService]
inside @Component
decorator of the components that will inject DataService to use.
And in the tutorial, we implement code with the approach:
... @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [DataService] }) export class AppComponent implements OnInit { ...
Re-implement getCustomers()
:
getCustomers() { return this.dataService.getCustomers().then(customers => this.customers = customers); }
this.dataService.getCustomers()
will return Promise.then(...)
to resolve returned data as Customer[].
Full Code:
import { Component, OnInit } from '@angular/core'; import { Customer } from './customer'; import { DataService } from './data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [DataService] }) export class AppComponent implements OnInit { customers: Customer[]; selectedCustomer: Customer; constructor(private dataService: DataService) {} getCustomers() { return this.dataService.getCustomers().then(customers => this.customers = customers); } ngOnInit(): void { this.getCustomers(); } onSelect(cust: Customer): void { this.selectedCustomer = cust; } }
2.4. Use Twitter Bootstrap to modify Component’s views
Now, we can use Twitter Bootstrap to make up the Angular-App.
– Open file /angular4client/src/index.html then add Twitter Bootstrap’s stylesheet:
<html> <head> ... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body class="container"> <app-root>Loading...</app-root> </body> </html>
– Edit AppComponent‘s template app.component.html:
<h2 style="color:blue">My Customers</h2> <ul class="list-group"> <li *ngFor="let cust of customers" class="list-group-item list-group-item-info" [class.selected]="cust === selectedCustomer" (click)="onSelect(cust)"> <span style="color:blue">{{cust.id}} - {{cust.firstname}}</span> </li> </ul> <customer-detail [customer]="selectedCustomer"></customer-detail>
3. Run & check results
Run the Angular App with commandline npm start
. Then make a request http://localhost:4200/
-> Check results:
– Customer List:
– Customer Details: