Angular Component is used to present data and delegate data access to a service. Angular Services are a great way to share data among classes. So in the tutorial, we introduce how to create Angular Service and use Observable
class of RxJS library for asynchronous operation in Angular Service’s implementation.
Related posts:
– Angular 11 Component – How to create & integrate New Angular 11 Component
– Angular 11 Routing/Navigation – with Angular Router Service
– How to Integrate Angular 11 & SpringBoot 2.0 RestAPI – SpringToolSuite
Technologies
- Node.js – version v10.4.0
- Angular – version 6
- Visual Studio Code – version 1.24.0
Practice
Generate Project Structure
Generate Angular Project:
ng new angular6-service
Generate Customer Component:
ng generate component customer
Generate Customer Service:
ng generate service customer
Generate Customer classes:
ng generate class customer ng generate class mock-customers
-> Project Structure:
Implement Mock Data
Create data class in src/app/customer.ts file:
export class Customer { id: number; firstname: string; lastname: string; age: number }
Mock Customer data in src/app/mock-customers.ts 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} ];
Implement Angular Service
-> First look src/app/customer.service.ts file:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CustomerService { constructor() { } }
@Injectable
decorator is a marker metadata that marks a class as available to Injector for creation.
Now, modify customer.service.ts file as below:
import { Injectable } from '@angular/core'; import { Customer } from './customer'; import { CUSTOMERS } from './mock-customers'; @Injectable({ providedIn: 'root' }) export class CustomerService { constructor() { } getCustomers(): Customer[] { return CUSTOMERS; } }
Update Angular Components
Firstly, import CustomerService
:
import { CustomerService } from '../customer.service';
Inject the CustomerService
:
constructor(private customerService: CustomerService) { }
-> Now, We can use customerService
as a CustomerService
injection.
Fetch data from CustomerComponent
via CustomerService
:
ngOnInit() { this.customers = this.customerService.getCustomers(); }
Full code in customer.component.ts file:
import { Component, OnInit } from '@angular/core'; import { CustomerService } from '../customer.service'; import { Customer } from '../customer'; @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./customer.component.css'] }) export class CustomerComponent implements OnInit { customers: Customer[]; constructor(private customerService: CustomerService) { } ngOnInit() { this.customers = this.customerService.getCustomers(); } }
In customer.component.html file, use Angular *ngFor
to display data:
<h1>Customer List</h1> <ul> <li *ngFor="let customer of customers"> {{ customer | json }} </li> </ul>
In AppComponent component, add selectỏr app-customer
tag in style file app.component.html:
<div> <app-customer></app-customer> </div>
-> Result:
Observable Data
What is the problem with above the service implementation?
-> CustomerService.getCustomers()
is a synchronous method. It will Not work with real application (with remote APIs, waiting time for responses).
Solution:
-> Observable
is a key class in the RxJS library which provides asynchronous operation.
Now, the sourcecode can be updated as below:
– With CustomerService, modify customer.component.ts
class:
import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { Customer } from './customer'; import { CUSTOMERS } from './mock-customers'; @Injectable({ providedIn: 'root' }) export class CustomerService { constructor() { } getCustomers(): Observable{ return of(CUSTOMERS); } }
– With CustomerComponent, modify customer.component.ts
class:
import { Component, OnInit } from '@angular/core'; import { CustomerService } from '../customer.service'; import { Customer } from '../customer'; @Component({ selector: 'app-customer', templateUrl: './customer.component.html', styleUrls: ['./customer.component.css'] }) export class CustomerComponent implements OnInit { customers: Customer[]; constructor(private customerService: CustomerService) { } ngOnInit() { this.customerService.getCustomers() .subscribe(customers => this.customers = customers); } }
SourceCode
How to run the below sourcecode:
1. Download Angular-6-Service.zip file -> Then extract it to Angular-6-Service folder. 2. Go to Angular-6-Service folder 3. Run the app by commandline: ng serve --open
-> Source Code: