Learn About Asynchronous Service In Angular

Introduction

In this article, we are going to see how to call asynchronous service in angular. The asynchronous service will subscribe to Observable or Promise and returns the latest value it has emitted. 

When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. 

After installing and setting up our application. Here I have created DataService. Inside the DataService added getDataList(), getDatabyId(), addData () and deleteData() methods. Please follow the codes below. 

import {MockData} from './../mock-data/mock-Data-data';  
import {Injectable} from '@angular/core';  
import {Data} from '../models/Data';  
import {Observable} from 'rxjs/Observable';  
import {of} from 'rxjs/observable/of'; 
@Injectable()
export class DataService {
    DataList: Data[] = [];
    constructor() {
        this.DataList = MockData.DataList;
    }
    getDataList(): Observable < Data[] > {
        return of(this.DataList);
    }
    addData(Data: Data) {
        this.DataList.push(Data);
    }
    getDatabyId(id: number): Observable < Data > {
        return of(this.DataList.find(p => p.id === id));
    }
    removeData(Data: Data) {
        let index = this.DataList.indexOf(Data);
        if (index !== -1) {
            this.DataList.splice(index, 1);
        }
    }
}

The getDataList() from DataService can fetch data synchronously. The DataComponent consumes the getDataList() result as if products could be fetched synchronously. Please follow the code below. 

this.datalist = dataService.getDataList(); 

The DataService must wait for the backend server to respond,  

getDataList() cannot return immediately with data, and the browser will not block the service waits. DataService.getDataList () needs to have an asynchronous signature. It will return a Promise or an Observable. 

ProductService.getDataList() must have an asynchronous It can take a callback. It could return a Promise or an Observable. 

We will update dataService.getDataList() which will return an Observable in part because we have used the Angular HttpClient.get() method to fetch the getDataList and HttpClient.get() returns in the Observable. 

Observable is one of the key classes in the RxJS library. We will learn Angular HttpClient methods that return RxJS Observables. We will simulate getting data from the server with the RxJS of () function. 

Next going to open the DataService file and import the Observable and symbols from RxJS. 

import {Observable} from 'rxjs/Observable'; 
import {of} from 'rxjs/observable/of'; 

replace getDataList() method of DataService with the code below. 

getDataList(): Observable<Data []> { 
    return of(this.datalist); 
} 

of(this.datalist) returns an Observable<Data []> that emits a single value, the array of mock datalist. 

Then Next going to add the Find the getDataList() method and replace it with the following code below. 

ngOnInit() {
    this.DataService.getDataList().subscribe(res => this.datalist = res);
}

Observable. Subscribe () is the critical difference. This asynchronous approach will work when the Data Service requests getDataList from the server. 

We will convert the getDataList() method with an asynchronous signature in DataService as shown below. 

getDatabyId(id: number): Observable { 
    return of(this.datalist.find( p => p.id === id)); 
} 

Please follow the subscribe this method in DataComponent as shown below. 

this.dataService.getDatabyId(id).subscribe( 
    res => this.datalist = res 
); 

The Observable to emit the array of getting at the list which could happen now or several minutes from now. Then subscribe passes the emitted array to the callback, which sets the component’s datalist property. 

Data.component.ts 

import {
    Dataervice
} from './../service/data.service';
import {
    Component,
    OnInit
} from '@angular/core';
import {
    Data
} from '../models/data';
@Component({
    selector: 'app-data',
    templateUrl: './data.component.html',
    styleUrls: ['./data.component.css']
})
export class DataComponent implements OnInit {
    datalist: Data[] = [];
    constructor(public dataService: DataService) {}
    ngOnInit() {
        this.getDataList();
    }
    deleteData(data: Data) {
        this.dataService.removeData(data);
        this.getDataList();
    }
    getDataList() {
        this.dataService.getDataList().subscribe(res => this.datalist = res);
    }
}

Once you add all the codes, please run the application using ng serve --open or npm start and check asynchronous-service function. 

I hope this article is very helpful for you. 


Similar Articles