AngularJS – how to use $http service


When we write code inside of a controller then we need to fetch data from web server and web server might need to talk to SQL database or XML files on desk and get back data from server in order to communicate to the server and it’s a job of $http service available in AngularJS. $http service is a build-in service that AngularJS provided and it’s just an Object with method we use to call http calls.

$http service provides methods like get(), post(), delete(), put(). Get method is used commonly to read data from the server where post(), put() and delete() methods used to modified data on server.

How to access $http service ?

Just like $scope we can pass $http to controller. Once you have $http inside your controller then you can use methods like $http.get(), $http.post() to communicate with webserver.

Remember, when you can of the $http service methods it doesn’t return the response immediately because it’s an asynchronous call to server. It rather returns a promise object. A promise object is an object which promises you to return the data in future. Data return by the promise will be a data that you need or some error. This promise has a then() method which will take a function as argument and call then function in future. The then() method call my function when the data is ready and pass the data into my function as a parameter.

AngularJS will invoke then(function(){}) when the response is successful. If there is an error then you can pass a second parameter to then() which will be invoked when an error occur. Following is a code snippet for both success and error condition.

Another way to use $http service is calling success(), error() functions on promise. Following code snippet will demonstrate this approach.

Create a simple PHP file which return an json encoded array containing user profile details.

Now, create a angular controller and call the service.

Finally, your HTML page should looks like below to display that service result back into HTML tags.

Run this program on any PHP server and you will get the result like below.

Hope you enjoy the post and learn AngularJS $http service. :)

About the Author

has written 67 posts.

I Love Coding, Analyzing, Designing and doing it the right way. I am obsessed about learn anything new daily and sharing what I have learn each Day. This Blog is journey of my Zeal, going through step by step to the mountain of desire to become prefect. Google Wanna Hire me ?

Copyright © 2017 TechZoo - Technology Blog. All rights reserved.
Proudly powered by WordPress. Developed by 7Tech Solutions