Chi*_*hah 14 javascript angularjs typescript
我正在使用Asp.Net Web API和AngularJS开发SPA.我还使用TypeScript来获取静态类型.所以,我添加了DefinitelyTyped angularjs.
因为我正在使用RESTfull服务.我想过使用angularjs的$资源.现在我的资源没有PUT http方法的任何内置方法.所以我决定添加我自己的如下.
var employees = $resource('/api/employee/:id',{id:'@id'},{"update":{ method: "PUT", isArray:false }};
Run Code Online (Sandbox Code Playgroud)
现在,正如您所看到的,在普通的AngularJS中很容易做到.我想通过TypeScript路由并定义扩展IResourceClass的自定义接口.这个界面的文档解释如下.
//具有默认操作的每个资源的基类.//如果为资源定义新操作,则需要//扩展此接口并将ResourceClass类型转换为该接口.
我真的无法弄清楚如何扩展这个界面.它不断出现一些关于语法的错误.有人可以解释如何扩展此接口并添加Update方法,然后在我的控制器上调用PUT方法.
Sco*_*ott 29
首先定义您的模型,即描述您的员工的界面.
// Define an interface of the object you want to use, providing it's properties
interface IEmployee extends ng.resource.IResource<IEmployee>
{
id: number;
firstName : string;
lastName : string;
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个描述您将创建的资源的界面.
// Define your resource, adding the signature of the custom actions
interface IEmployeeResource extends ng.resource.IResourceClass<IEmployee>
{
update(IEmployee) : IEmployee;
}
Run Code Online (Sandbox Code Playgroud)
创建EmployeeResource
工厂:
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 <IEmployeeResource> $resource('/api/employee/:id', { id: '@id' }, {
update: updateAction
});
}]);
Run Code Online (Sandbox Code Playgroud)
将您EmployeeResource
注入控制器:
myApp.controller('TestCtrl', ['$scope', 'EmployeeResource', ($scope, Employee : IEmployeeResource) =>
{
// Get all employees
var employees : Array<IEmployee> = 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" });
}]);
Run Code Online (Sandbox Code Playgroud)
创建新的员工实例:
您可以创建类型的实例IEmployee
由new
荷兰国际集团的EmployeeResource
工厂.
myApp.controller('TestCtrl', ['$scope', 'EmployeeResource', ($scope, Employee : IEmployeeResource) =>
{
var myEmployee : IEmployee = new Employee({ firstName: "John", lastName: "Smith"});
myEmployee.$save();
}
Run Code Online (Sandbox Code Playgroud)
所以在上面的例子中我们注入了IEmployeeResource
as Employee
.然后我们可以通过new
这个对象创建一个IEmployee
.
归档时间: |
|
查看次数: |
9868 次 |
最近记录: |