Angular 11 Observable Service for Asynchronous Operation

https://grokonez.com/angular-11-observable-service-for-asynchronous-operation

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:

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

angular-6-services + create-angular6- project

Generate Customer Component:

ng generate component customer

angular-6-services + create-a-component-customer

Generate Customer Service:

ng generate service customer

angular-6-services + create-an-angular-6-service-customer

Generate Customer classes:

ng generate class customer
ng generate class mock-customers

angular-6-services + generate-angular-6-class

-> Project Structure:

angular-6-services + angular-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:

angular-6-services + load-data-from-service-synchronize-operation

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:

Angular-6-Service

https://grokonez.com/angular-11-observable-service-for-asynchronous-operation

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

Male avatar

loveprogramming

187 bài viết.
63 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
Male avatar
1 0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...
loveprogramming viết 5 tháng trước
1 0
Male avatar
1 0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...
loveprogramming viết 4 tháng trước
1 0
Male avatar
1 0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
loveprogramming viết 4 tháng trước
1 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


Male avatar
{{userFollowed ? 'Following' : 'Follow'}}
187 bài viết.
63 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!