AngularJS in TypeScript: $resource

$resource factory is very useful if the server-side data service is RESTful.

With TypeScript, it will be much better because we can strongly typed data returned from server.

Here is an example on how I implement $resource using TypeScript

Create interface for object and resource object
module Test { 
  export interface IClient extends ng.resource.IResource<IClient> {
      id: number;
      name: string;
  export interface IClientResource extends ng.resource.IResourceClass<IClient> {

In the above code, I create two interfaces, IClient and IClientResource. IClient contains properties of the object, while IClientResource contains resource actions. Resource Object already has default actions from $resource.

Create Factory
module Test {
    export class Resource {
        public static Client($resource: ng.resource.IResourceService): IClientResource {
            var url = "http://localhost/Clients/";
            var resource = $resource("", {},
                'query': { method: 'GET', url: url },
                'get': { method: 'GET', params: { id: "@id" }, url: url + "(:id)" },
                'save': { method: "POST", url: url },
                'remove': { method: 'DELETE', params: { id: "@id" }, url: url + "(:id)" }

            return <IClientResource> resource;
app.factory('Client', ['$resource', Test.Resource.Client]);

I only use static method because my factory only needs $resource actions.

And that's all I need to do. I can use this factory on other angular service to call the REST service

For more details, the full sample is available on my GitHub

Abdurrachman Habibi

Read more posts by this author.