Skip to main content

Implement a Service From Angular (Http Observables and Rxjs)


What is a Service in Angular?

Angular services are singleton objects which get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time. The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application.

What is Rxjs ?

It is a Reactive Extensions for JavaScript. Also external library to work with Observables. 

Implementation

So now we are going to create a service using Http Observables and Rxjs. Basically there are four main steps to do that.


1. Http get request from service.
2. Receive the observable and cast it into an array.
3. Subscribe to the observable component.

Now I'm going to implement a service for fetching data from server to our web page. 

First Step

1.1  Import HttpClientModule for app.module.ts



I created a Service call employee. This employee is use to fetch data from server.

1.2  Import HttpClientModule for employee.service.ts



1.3 In this case I don't go to work with server. For that I use local Json file to store our data. But this is the same way to work with server. only thing you have to do is give the server path.

I create a folder call "data" under the "src".  Then I create json file call employee.json under following directories ("src/asset/data/employee.json").


Now my data file is employee.json. I insert some data to it.


1.4 Now declare the path of our data file(employee.json) as _url in employee.service.ts.
1.5 Declare a HttpClilent as a dependency in constructor of employee.service.ts
1.6 Declare a method (getEmployee) to fetch data from our employee.json file.


For now we completed successfully First Step.

Second Step

2.1 Now we should create Interface to fetch data. I create file under the "app" directory call employee.ts



2.2 And I create an interface call IEmployee in that file. I want to fetch id, name, age from employee.json



2.3 Now we should import this IEmployee interface and Observable to employee.service.ts.
2.4 Also we need to set observable object to our getEmployee() method. It's do like this.


Now we successfully finished our Second Step.

Third Step

3.1 I will show fetched data in employeelist component. So you should create employeelist component.
3.2 First of all you should create an array to store fetched data in employeelist.component.ts. In my case I create employees and it should be public.
3.3 Then declare a object from employee service in the constructor.
3.4 Access the getEmployee method in ngOnInt() . Inside this method process is assign values to local array.


It's look like very cool. Now we completed all the process. Only thing we have to do is call them.

Fourth Step

Now we have to use our employeelist.component.html to print the array values.

4.1 ngFor is a loop in Angular. We are going to fetch set of data. So we need to loop for print them.
Our target is print all the data in emplyee array. So our condition is "let employee from employees".
employee is a variable. employees is our array.


Don't remember to call to employeelist component from app.component.html. 



Done & Dusted. You have to run your project now. Here we go :)


Like wise you can write any service from this basic example. Thanks * :)

Comments

Popular posts from this blog

Building a RESTful CRUD API with Node.js, Express, MongoDB

Used Libraries Express Validator Mongoose _____________Just 3 Steps________________ Step 1 Initialize the project npm init -y npm install --save-dev nodemon npm install express mongoose npm install validator Now go to the package.json and modifiy the scripts property like this. Then create folder call utils and create a file call db.js inside it. Here is my project structure. If  you haven't any idea to get MongoDB Connection String please refer first part from  here. Follow these set of code for RESTful API crud operations.    Step 2     db.js const mongoose = require('mongoose'); const validator = require('validator'); const url = 'MongoDB Connection String'; mongoose.connect(url,{useUnifiedTopology:true,useNewUrlParser:true}); const Schema = mongoose.Schema; const userSchema = new Schema({     name : {         type : String,         require : true,         trim : true     },     age : {         type

Routing and navigation in Angular

Angular provides a complete  routing  library with the possibility to  have  multiple  router  outlets, different path matching strategies, easy access to  route  parameters and  route  guards to protect components from unauthorized access. The  Angular router is  a core part of the  Angular  platform. It's very easy to implement routing and navigation. So now I'm going to implement simple application for routing. When we create project it also create  app-routing.module.ts file. Then I created 2 components call DepartmentList and EmployeeList. So now what I want is when I Press the the Employee list button I want to move Employee List form and when press the Department list button  want to  move Department List form. First step You must go to the  app-routing.module.ts  and you can see there is an array call routes. Then declare your components with name which you want appear on URL.   Don't remember import your component. And you must export your components.

An Introduction to Mongoose, Express for MongoDB With NodeJS

This is about how to connect with MongoDB from NodeJS. Used Libraries Express  Mongoose Steps... 1. npm init -y 2. npm install --save-dev nodemon              coppy this inside package.json                 "scripts":{                   "start": "node app",                  "dev": "nodemon app"           } 3. npm i express mongoose db.js (Inside the utils folder) const mongoose = require('mongoose'); const validator = require('validator'); const url = 'MongoDB Connection String'; mongoose.connect(url,{useUnifiedTopology:true,useNewUrlParser:true}) .then(res => console.log(res)) .catch(err => console.log(err)); app.js const express = require('express'); require('./utils/db'); const app = express(); app.listen(3000);  For execute npm run dev