Tuesday, July 7, 2015

$resource service in AngularJS

The $resource service is a factory built on top of the $http service, $resource make is easy for us to perform CRUD operations calls to the service side APIs, it is not part of the main angular.js file, to use it we need to include the angular-resource.js file.

$resource works with a Restful API service at the server end, it supports GET, POST, PUT and DELETE operations. It is recommended that we wrap the API calls to the server in a factory while using $resource.

The following example shows how to make a HTTP Get API call using $resource and populate the view with the response from the API call.

<html ng-app="resourceApp">
    <meta charset="utf-8">
    <title>AngularJS - Basic</title>
<div ng-controller="resourceController">
          <li ng-repeat="package in packageList">
            {{ package.PackageId }} - {{ package.Name }}<br/>
    <script src="angular.min.js"></script>
    <script src="angular-resource.min.js"></script>
          <script src="resourceAjax.js"></script>

var app = angular.module("resourceApp", ["ngResource"])
.factory('packageResource', function($resource){
    return $resource('http://localhost:7630/api/Package', {})
app.controller("resourceController", function($scope,packageResource) {
    $scope.Title = "Package List";
    $scope.packageList = {};
          packageResource.query(function(response) {
                $scope.packageList = response;


Search Flipkart Products:

No comments: