Angular 7 | Angular Data Services using Observable
Last Updated :
28 Apr, 2025
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
To run this application migrate inside the project and run the following command.
cd < Project Path >
ng serve -o
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read