Skip to content
Related Articles

Related Articles

Improve Article

Angular 7 | Angular Data Services using Observable

  • Last Updated : 06 Oct, 2020

Observables 

Observable manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. Unlike Promises, Observables emit multiple values over time. In real scenarios, web socket or real-time based data or event handlers can emit multiple values over any given time. In such a case Observables are the best option to use. 
 
In angular, Observables are one of the most used techniques and is used extensively in integration with Data Services to read a REST API. Other than that, to access an observable, the component first needs to subscribe to the Observable. It is important to do this to access the data in observable REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing the web services simply and flexibly without having any processing. To read more you can navigate to this link. 

Services

Services are used to create variables/data that can be shared and can be used outside the component in which it is defined. A service can be used by any component and thus it acts as a common data point from which data can be distributed to any component in the application. To read more about services follow this link.

To add a service write the following command in the console. 

ng g s ServiceName
OR
ng generate service ServiceName

Example: 
 This is a small example of a service named Data in which an event happening in the component will trigger the method of the service.



The data.service.ts code  

Javascript




import { Injectable } from '@angular/core';
 
@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
 
  constructor() { }
clickEvent(){
  console.log('Click Event');
}
}

The app.component.ts code 

Javascript




import { Component } from '@angular/core';
import {DataServiceService} from './data-service.service'
@Component({
  selector: 'app-root',
  template: '<html>
                       <body>
<button (click)="clickEvent()" style="width:50px;height:30px">Button</button>
                       </body>
               </html>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private Data: DataService) {
  }
function cEvent(){
  this.Data.clickEvent()
}
}

Output:  

Services With Observable: 
In combination, it is famous to work with REST API. In the following example there will be a Service in which an API will be accessed using GET request feature provided in the HttpClientModule in Angular, which in turn returns an observable. This observable will be subscribed by a component of the application and then shown on the page. 

Example: 
The data.service.ts 

Javascript




import { Injectable } from '@angular/core';
//Importing HttpClientModule for GET request to API
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class DataService {
 
  // making an instance for Get Request
  constructor(private http_instance: HttpClient ) { }
  // function returning the observable
  getInfo(){
    return this.http_instance.get('https://reqres.in/api/users')
  }
}

The reg-user.component.ts  

Javascript




import { Component, OnInit } from '@angular/core';
// Importing Data Service to subscribe to getInfo() observable
import { DataServiceService } from '../data-service.service'
@Component({
  selector: 'app-reg-user',
  templateUrl: './reg-user.component.html',
  styleUrls: ['./reg-user.component.css']
})
export class RegUserComponent implements OnInit {
 
  // instantiation of local object and the Data Service
  inst : Object;
  constructor(private data: DataServiceService ) { }
 
  //Subscription of the Data Service and putting all the
  // data into the local instance of component
  ngOnInit() {
    this.data.getInfo().subscribe((data)=>{
      this.inst=data;
    })
  }
 
}

The Directives Used in Html of RegUserComponent  

Javascript




<style>
ul {
    list-style-type: none;
    margin: 0;padding: 0;
}
 
    ul li {
        background: rgb(238, 238, 238);
        padding: 2em;
        border-radius: 4px;
        margin-bottom: 7px;
        display: grid;
        grid-template-columns: 60px auto;
    }
 
       ul li p {
            font-weight: bold;
            margin-left: 20px;
        }
 
       ul li img {
            border-radius: 50%;
            width: 100%;
        }
     
 
</style>
<h1>Users</h1>
 
<ul *ngIf="inst">
  <li *ngFor="let user of inst.data">
    <img [src]="user.avatar">
     
<p>{{ user.first_name }} {{ user.last_name }}</p>
 
  </li>
</ul>

Output:  

Accessing API

Accessing API

 To run this application migrate inside the project and run the following command.

cd < Project Path >
ng serve -o

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :