Last active
August 29, 2015 14:06
-
-
Save Hotell/5307cd5de1c01b05e3e8 to your computer and use it in GitHub Desktop.
Custom ng.resource definition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We have the option to define arguments for a custom resource | |
interface IArticleParameters { | |
id: number; | |
} | |
interface IArticleResource extends ng.resource.IResource<IArticleResource> { | |
title: string; | |
text: string; | |
date: Date; | |
author: number; | |
// Although all actions defined on IArticleResourceClass are avaiable with | |
// the '$' prefix, we have the choice to expose only what we will use | |
$publish(): ng.IPromise<IArticleResource>; | |
$unpublish(): ng.IPromise<IArticleResource>; | |
} | |
// Let's define a custom resource | |
interface IArticleResourceClass extends ng.resource.IResourceClass<IArticleResource> { | |
// Overload get to accept our custom parameters | |
get(): IArticleResource; | |
get(params: IArticleParameters): IArticleResource; | |
// Add our custom resource actions | |
publish(): IArticleResource; | |
publish(params: IArticleParameters): IArticleResource; | |
unpublish(params: IArticleParameters): IArticleResource; | |
} | |
var app = angular | |
.module('ngResourceTypings', ['ngResource']) | |
.controller('MainController', MainController); | |
function MainController($resource: ng.resource.IResourceService) { | |
// IntelliSense will provide IActionDescriptor interface and will validate | |
// your assignment against it | |
var publishDescriptor: ng.resource.IActionDescriptor; | |
publishDescriptor = { | |
method: 'GET', | |
isArray: false | |
}; | |
// I could still create a descriptor without the interface... | |
var unpublishDescriptor = { | |
method: 'POST' | |
}; | |
// A call to the $resource service returns a IResourceClass. Since | |
// our own IArticleResourceClass defines 2 more actions, we cast the return | |
// value to make the compiler aware of that | |
var articleResource = $resource<IArticleResource, IArticleResourceClass>('/articles/:id', null, { | |
publish: publishDescriptor, | |
unpublish: unpublishDescriptor | |
}); | |
// Now we can do this | |
articleResource.unpublish({id: 1}); | |
// IResourceClass.get() will be automatically available here | |
var article: IArticleResource = articleResource.get({id: 1}); | |
article.$promise.then(function success() { | |
// Again, default + custom action here... | |
article.title = 'New Title'; | |
article.$save(); | |
article.$publish(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment