Extending $resource of angularjs using IResourceClass of typescript

后端 未结 2 673
眼角桃花
眼角桃花 2021-02-13 10:26

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

2条回答
  •  孤城傲影
    2021-02-13 11:09

    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 newing 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.

提交回复
热议问题