Angular 2 HTTP Requests and Observables

Share On Facebook
Share On Google Plus
Share On Linkedin
Contact us

     Observables are basically the ES7(2016) feature implemented in Rxjs library.i.e. Reactive Extensions for the JavaScript. We use observables in Angular 2 by importing it from the rxjs library. Angular 2 provides such a wonderful features that makes application development a charm. We are going to learn how to make HTTP Requests in Angular 2 using Rxjs Observable library.

Little Bit About Angular 2 Observables

     Observable are similar to the Promises in AngularJS but with some differences.

  1. Observables handle multiple values over the time, while Promise return only single value.
  2. Observables can be cancelled, while the Promises not. Lets talk about the case, Suppose we are implementing the Autocomplete feature. on each key press event we supposed to send the requests to fetch the results. On typing Observable, the results of key ‘O’ will come after ‘ob’, then it will make the result set very messy, we may want to cancel the requests of key ‘o’. So here Observables shines.

Observables comes with many operators, most of popular are map, filter, etc. I am using Map in this tutorial. Observable makes very easy to make cool stuff very easy.

Lets Come up with the Angular 2 HTTP tutorial

     Today I am going to build up Task To do list, where I can add Tasks, also Edit, Delete the tasks, set completed the Task once it completed and also, I can move up and move down the Task i.e. setting up the priorities of the tasks.
Checkout the screenshot of Application:-

Todo Application FrontEnd Html
     I am using the Django, a Python framework for the back-end of application. It is out of the scope of this tutorial. You can get information about Django from here. Django makes it very easy to make REST API. So I used it.
     To install Django, here is the reference and this is the link of my Git Repository.

  • Clone the repo,
  • cd todoApp/
  • virtualenv .
    This make a virtual environment for the project.
  • source bin/activate
    Activate the virtual environment
  • pip install -r requirements.txt
    All project dependencies will be installed.
  • python manage.py runserver
    It starts the back-end server. Go to http://127.0.0.1:8000/ to see it.

Back-end of the Application
Here is my front-end code GIT Repository, that I am building. https://github.com/tusharcoder/todoApp-frontend Clone it and run it. Steps:-

  • Clone my repo
  • cd todoApp-frontend/
  • npm install
    All npm dependencies will be installed .
  • ng serve
    This will start the frontend application server. Go to http://127.0.0.1:4200/ to see the application.

*Before run it make sure you have Angular cli installed, get reference from here

Let’s Build Application step by step:-

  • Make Project directory mkdir todoApp-frontend
  • Initialize Angular 2 Project ng init

     Might need to run nvm use stable first. I am using nvm (Node version manager) to manage the versions of the node, or npm. So before running any npm related, or angular related commands, I have to run nvm use stable for the first time in every terminal session.
ng init makes the initial set up of the the application. As we will not to worry about of setting up the application and related, npm packages and importing them. Its all done by the above command.It takes sometime, so be patient.
ng init - initialize Angular 2 Project
     We have the initial set up of the application. Lets scaffolding all the components that we need in our application.

Scaffolding all Angular 2 components

     I am using Angular CLI generators to generate different components, services, modules etc as required. Click for More Info.

EventChanges service

     For accomplishing this make EventChanges service by command ng g service EventChanges

make service by angular 2 generator
add code to the /src/app/emit-changes.service.ts file

Basic Idea is to make a central event handling hub that contains all the events information bind to an Id in say ‘_emitters’ property. If it has the event with the given id it will return or if not it will create and return the EventEmitter object by using the get function:-

TaskService

     This will have all the Http requests (GET,PUT,POST,DELETE) need to get, update, create and delete the task. Run command ng g service TaskService
task service by angular cli generator

Add code to file /src/app/task.service.ts

Task Form

Run ng g component TaskForm
task form component by angular cli generator
Add code to src/app/task-form/task-form.component.ts

and add component html to src/app/task-form/task-form.component.html

So we have html form for creating task, updating task depending on the editmode property. Add the new task if editmode if off i.e false and update if it is on i.e. true.
     Basic idea is to use EventEmitter to emit events, i.e. task is add to the task list, or task has to be edited, listevent, editEvent emitted respectively. So actually what is going on, The scope data is injected from the parent and grandparent component to the child components and when there is any change in the child component, parent or respective grandparent will be notified about the change occurred. Respond in turn of it, eg: task is added to task list, event emitted and list is refresh by the parent component on catching the event.

Task List

It will contain the list of the tasks, task with the higher priority at the top. Run ng g component TaskList
task list component by angular cli generators
Add code to /src/app/task-list/task-list.component.ts

And component html to /src/app/task-list/task-list.component.html

This component will show the tasks in list priority wise. Here we can set completed the task, edit, delete and move up and down the task, increase or decrease their priority.This component implement both onInit and OnChanges. On removal, completion of any task, list event bind to the listId is emitted and catched by the ngOnChanges method and refresh the list. See Change in the child occurs and the parent component i.e. the list knows it has to be refreshed to reflect the changes. So how wonderful is it. This way the component knows when and how it has to respond to the change.
     On click the update button of any task, it emits the edit event that will be cached by the task form component ngOnChanges method and set the editmode to true and also set the model with that of the passed payload or say the task. So this way the components interacts with each other and respond to the changes.

Task Widget

This component works as the wrapper for the task form and the task list component, and inject the listId and the editId to its child components. This way the task list and the task form component get the listId and editId input. Run command ng g component TaskWidget
task widget component generated by angular cli generators
Add code to the /src/app/task-widget/task-widget.component.ts

And html to /src/app/task-widget/task-widget.component.html

You should have noticed that I use bootstrap classes through out the html, so include bootstrap by CDN in the index.html page:-

Task Model

     We have made all components, but forget Task Model, whose objects we create, edit, delete in our application. Lets Create it by:-
ng g class Task
Add code to the file todoApp-frontend/src/app/task.ts


Now our task widget is ready to run. But For that, it has to be exported as a module. That will be imported in our application, so lets make a task Module.

Task Module

Run command ng g module Task
Task module by angular cli generators
and add code to /src/app/task/task.module.ts

Here I provide the TaskService in the providers, so that it can be used, also exported all the Components i.e TaskList, TaskForm, and The TaskWidget, so that they will not need to imported to use. I just have to import Task module, and they are automatically imported and ready to use. The difference between the App and the module is that The App has to be bootstrapped, while module not. So we bootstrap our application using AppComponent.:-
Bootstrapping Angular 2 Application

Our Task module is ready now, we just need to import in our Application to run. Add code to the /src/app/app.module.ts

and html to /src/app/app.component.html

Have a look at task-widget.component.ts:-
Angular 2 component selector for task widget
task-widget is the selector which we use in app.component.html as an html tag to show up in the web page.:-
Angular 2 component selector usage for task widget

I also added a nice background to the app. So go to index.html and update the code as:-

and also add the background image file download from here
to /src/assets/ folder.

Run command
ng serve
Serve the Angular 2 Application
also make sure that your Django backend server is running at http://127.0.0.1:8000/ or http://localhost:8000/
if not then go to the back-end project directory, activate virtual environment by source bin/activate command
Activate virtual environment Django
and then run python manage.py runserver 127.0.0.1:8000 or python manage.py runserver localhost:8000
Start Django server - runserver
Go to localhost:4200 and you find your app working.
Todo Application FrontEnd Html
So, Today we learn how to do HTTP Requests in Angular 2 with Observables and how the components respond to the change using the EventEmitter imported from @angular/core.

For more tutorials Keep visiting this site and also check my Git repositories from https://github.com/tusharcoder?tab=repositories

8 thoughts on “Angular 2 HTTP Requests and Observables

Leave a Reply

Your email address will not be published. Required fields are marked *