I am developing SPA using Asp.Net Web API and AngularJS. I also use TypeScript to get static typing. So, I added DefinitelyTyped angularjs.
As I am using RESTfull servic
First define your model, the interface that will describes your employee.
// Define an interface of the object you want to use, providing it's properties
interface IEmployee extends ng.resource.IResource
{
id: number;
firstName : string;
lastName : string;
}
Then create an interface that describes the resource you will create.
// Define your resource, adding the signature of the custom actions
interface IEmployeeResource extends ng.resource.IResourceClass
{
update(IEmployee) : IEmployee;
}
Create the EmployeeResource
factory:
var myApp = angular.module('myApp', ['ngResource']).factory('EmployeeResource',
['$resource', ($resource : ng.resource.IResourceService) : IEmployeeResource => {
// Define your custom actions here as IActionDescriptor
var updateAction : ng.resource.IActionDescriptor = {
method: 'PUT',
isArray: false
};
// Return the resource, include your custom actions
return $resource('/api/employee/:id', { id: '@id' }, {
update: updateAction
});
}]);
Inject your EmployeeResource
into a controller:
myApp.controller('TestCtrl', ['$scope', 'EmployeeResource', ($scope, Employee : IEmployeeResource) =>
{
// Get all employees
var employees : Array = Employee.query();
// Get specific employee, and change their last name
var employee : IEmployee = Employee.get({ id: 123 });
employee.lastName = 'Smith';
employee.$save();
// Custom action
var updatedEmployee : IEmployee = Employee.update({ id: 100, firstName: "John" });
}]);
Creating a new employee instance:
You can create an instance of type IEmployee
by new
ing the EmployeeResource
factory.
myApp.controller('TestCtrl', ['$scope', 'EmployeeResource', ($scope, Employee : IEmployeeResource) =>
{
var myEmployee : IEmployee = new Employee({ firstName: "John", lastName: "Smith"});
myEmployee.$save();
}
So in the case above we inject our IEmployeeResource
as Employee
. We can then new
this object to create an IEmployee
.