Using $resource for RESTful services

Loading

What You’ll Learn:

What is $resource in AngularJS?
How to use $resource for CRUD operations in RESTful APIs
Configuring $resource with custom methods
Example of implementing $resource in an AngularJS app


1️⃣ What is $resource in AngularJS?

🔹 $resource is an AngularJS service that simplifies interactions with RESTful APIs.
🔹 It is built on top of $http and provides an easier way to perform CRUD operations.
🔹 $resource is part of ngResource module, which must be included in your AngularJS app.


2️⃣ How to Use $resource for RESTful APIs

Step 1: Include ngResource Module

Before using $resource, include the ngResource module in your AngularJS app:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-resource.min.js"></script>

Step 2: Add ngResource as a Dependency

Inject ngResource into your AngularJS module:

var app = angular.module("myApp", ["ngResource"]);

Step 3: Define a $resource Factory

Create a factory to interact with a REST API (e.g., /api/users).

app.factory("UserService", function ($resource) {
return $resource("/api/users/:id", { id: "@id" }, {
update: { method: "PUT" }
});
});

🔹 How It Works:

  • /api/users/:id:id is a placeholder for dynamic values.
  • { id: "@id" } → Maps object properties to URL parameters.
  • update: { method: "PUT" } → Defines a custom update method using HTTP PUT.

3️⃣ CRUD Operations Using $resource

1️⃣ Fetch All Users (GET /api/users)

app.controller("UserController", function ($scope, UserService) {
$scope.users = UserService.query(); // Fetch all users
});

🔹 $resource.query() fetches all records from the API.


2️⃣ Fetch a Single User (GET /api/users/:id)

$scope.user = UserService.get({ id: 1 }); // Fetch user with ID = 1

🔹 How It Works:

  • The id parameter replaces :id in /api/users/:id.
  • The API responds with the user’s data.

3️⃣ Create a New User (POST /api/users)

var newUser = new UserService();
newUser.name = "John Doe";
newUser.email = "john@example.com";

newUser.$save(function (response) {
console.log("User created:", response);
});

🔹 $save() sends a POST request with the new user’s data.


4️⃣ Update a User (PUT /api/users/:id)

var user = UserService.get({ id: 1 }, function () {
user.name = "Updated Name";
user.$update(); // Calls the custom update method (PUT request)
});

🔹 Uses the update method defined in the factory.


5️⃣ Delete a User (DELETE /api/users/:id)

UserService.delete({ id: 1 }, function () {
console.log("User deleted");
});

🔹 Sends a DELETE request to remove the user from the database.


4️⃣ Full Example: User Management App

User Factory (Service Layer)

app.factory("UserService", function ($resource) {
return $resource("/api/users/:id", { id: "@id" }, {
update: { method: "PUT" }
});
});

User Controller

app.controller("UserController", function ($scope, UserService) {
// Fetch all users
$scope.users = UserService.query();

// Create a new user
$scope.addUser = function () {
var newUser = new UserService($scope.newUser);
newUser.$save(function () {
$scope.users = UserService.query(); // Refresh list
});
};

// Update user
$scope.updateUser = function (user) {
user.$update();
};

// Delete user
$scope.deleteUser = function (userId) {
UserService.delete({ id: userId }, function () {
$scope.users = UserService.query(); // Refresh list
});
};
});

User Interface (HTML)

<div ng-controller="UserController">
<h2>User Management</h2>

<form ng-submit="addUser()">
<input type="text" ng-model="newUser.name" placeholder="Name" required />
<input type="email" ng-model="newUser.email" placeholder="Email" required />
<button type="submit">Add User</button>
</form>

<ul>
<li ng-repeat="user in users">
{{ user.name }} ({{ user.email }})
<button ng-click="updateUser(user)">Update</button>
<button ng-click="deleteUser(user.id)">Delete</button>
</li>
</ul>
</div>

5️⃣ Summary of $resource CRUD Methods

ActionHTTP Method$resource MethodExample Usage
Get all usersGET.query()UserService.query()
Get a userGET.get()UserService.get({ id: 1 })
Create userPOST.$save()new UserService().$save()
Update userPUT.$update()user.$update()
Delete userDELETE.delete()UserService.delete({ id: 1 })

6️⃣ Advantages of $resource

Simplifies API requests: Reduces the need to manually write $http requests.
Less boilerplate code: CRUD operations are easier to implement.
More readable: $resource makes API calls more structured and maintainable.
Supports custom methods: You can define PUT, PATCH, or other custom endpoints.

Leave a Reply

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