Giter VIP home page Giter VIP logo

angular2-rest's Introduction

angular2-rest

Angular2 HTTP client to consume RESTful services. Built on angular2/http with TypeScript.
Note: this solutions is not production ready, it's in a very basic alpha state. Any ideas or contributions are very welcomed :)

Installation

npm install angular2-rest

Example

import {Request, Response} from 'angular2/http';
import {RESTClient, GET, PUT, POST, DELETE, BaseUrl, Headers, DefaultHeaders, Path, Body, Query} from 'angular2-rest';

import {Todo} from './models/Todo';
import {SessionFactory} from './sessionFactory';

@Injectable()
@BaseUrl("http://localhost:3000/api/")
@DefaultHeaders({
    'Accept': 'application/json',
    'Content-Type': 'application/json'
})
export class TodoRESTClient extends RESTClient {

    protected requestInterceptor(req: Request) {
        if (SessionFactory.getInstance().isAuthenticated) {
            req.headers.append('jwt', SessionFactory.getInstance().credentials.jwt);
        }
    }
    
    protected requestInterceptor(req: Response) {
        // do sg with responses
    }

    @GET("todo/")
    public getTodos( @Query("sort") sort?: string): Observable { return null; };

    @GET("todo/{id}")
    public getTodoById( @Path("id") id: string): Observable { return null; };

    @POST("todo")
    public postTodo( @Body todo: Todo): Observable { return null; };

    @PUT("todo/{id}")
    public putTodoById( @Path("id") id: string, @Body todo: Todo): Observable { return null; };

    @DELETE("todo/{id}")
    public deleteTodoById( @Path("id") id: string): Observable { return null; };

}

Using it in your component

@Component({
  selector: 'to-do',
  viewProviders: [TodoRESTClient],
})
@View({
  templateUrl: 'components/to-do-template.html',
})
export class ToDoCmp {

  constructor(todoRESTClient: TodoRESTClient) {
  }
  
  //Use todoRESTClient   
}

API Docs

RESTClient

Methods:

  • getBaseUrl(): string: returns the base url of RESTClient
  • getDefaultHeaders(): Object: returns the default headers of RESTClient in a key-value pair

Class decorators:

  • @BaseUrl(url: string)
  • @DefaultHeaders(headers: Object)

Method decorators:

  • @GET(url: String)
  • @POST(url: String)
  • @PUT(url: String)
  • @DELETE(url: String)
  • @Headers(headers: Object)

Parameter decorators:

  • @Path(key: string)
  • @Query(key: string)
  • @Header(key: string)
  • @Body

License

MIT

angular2-rest's People

Contributors

discountrobot avatar mmrath avatar nilpferdschaefer avatar paldom avatar tn-kirontech avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular2-rest's Issues

Can't resolve 'angular2-rest'

I used angular cli. I installed angular2-rest npm install angular2-rest.
I got an error :

ERROR in ./src/app/services/base-rest-client.service.ts
Module not found: Error: Can't resolve 'angular2-rest' in 'C:\Users\ankar\Projec
ts\hfs\components\src\app\services'
 @ ./src/app/services/base-rest-client.service.ts 16:0-73
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi main

Only json.stringify when the content type is application/json

Hey really nice library you have here.

I stumbled on an issue though and figured out that the body (added with @Body) is always passed to JSON.stringify(). It's a problem when you want to send something that is not json.
https://github.com/Paldom/angular2-rest/blob/master/angular2-rest.ts#L192

It's very convenient of course when you want to send JSON, which is the case most of the time. But IMO this process should only be done when the content type is set to application/json.

It would be awesome to support any other content type encoding...but quite cumbersome, so I suggest to let the user format the body the way he wants when the content type is not application/json.

Transforming the response

I'm new to observables and this service seems to use them heavily. I'd like to transform the response so that it creates a collection (on GET resource/) of entities implementing an interface describing them, or a single entity on GET resource/id.

The response from my API is something like this:

{
    data: [
        {
            id: 1,
            name: "some name"
        },
        {
            id: 2,
            name: "some name"
        },
    ],
    meta: {
        page: 1,
        totalPages: 14
    }
}

The method to receive this object is pretty basic:

@GET('/titles')
public getTitles(@Query('page') page: number): Observable<any>
{
    return null;
}

In my component which injects this Rest client, I use:

this.client.getTitles(page).subscribe(res => {
    console.log(res.json());
})

Now, I have two options:

  1. the ugly solution: Pass the res.json() results to another service in the observer callback which transforms the data array of the response to an array of entities. The downside is that I'd have to copy-paste this everywhere I want to get the data from the client.

  2. the nice solution: Somehow transform the response into entities in the client itself, then just pass the array of entities to the observer callback.

Any help is welcome.

Do you want to add tests?

Do you plan to add tests for this package? If so, would you prefer to use jasmine+sinonjs, jasmine+jasmine-ajax or something different? I would like to contribute, but without tests checking if something broke is tedious. I could write tests, if you don't mind for whatever reason.

enhancement: async requestInterceptor

The following code snippet will introduce a race condition, should one try to call SomeRESTClient before the _session has been populated, by the createSession request.

@Injectable()
@BaseUrl('https://api.someplace.com')
@DefaultHeaders({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
})
export class SomeRESTClient extends RESTClient {

  private _session: any

  constructor(private _http: Http) {
    super(_http)
    this.setup()
  }

  protected requestInterceptor(req: Request) {
    if (this._session) {
      req.headers.append('Token', this._session.token)
    }
  }

  @POST('/sessions')
  @Produces(MediaType.JSON)
  private createSession( @Body data ): Observable<any> { return null }

  private setup () {
    let api_key = 'xxxx'
    this.createSession({ api_key }).subscribe(session => this._session = session)
  }
}

We should add the possibility to have the requestInterceptor return a promise or similar.

Error at start

node_modules/angular2-rest/angular2-rest.d.ts(1,1): error TS2654: Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.
node_modules/angular2-rest/angular2-rest.d.ts(1,1): error TS6053: File 'node_modules/angular2-rest/node_modules/angular2/core.d.ts' not found.
node_modules/angular2-rest/angular2-rest.d.ts(2,1): error TS6053: File 'node_modules/angular2-rest/node_modules/angular2/http.d.ts' not found.
node_modules/angular2-rest/angular2-rest.d.ts(3,1): error TS6053: File 'node_modules/angular2-rest/node_modules/rxjs/Rx.d.ts' not found.

hi,like $resource in angular1

hi,there
thank you
i need this
I need it to replace $resource

:)

good job

i used django-rest-framework (django-rest-framework.org)
It can work it ?
thank you very much ,paldom

Please put up the latest version on npm

The current version doesn't work and throws: "ORIGINAL EXCEPTION: TypeError: observable.map is not a function" when I try to call my REST endpoint, but if I copy and paste the most recent angular2-rest.ts file and compile it then it works fine.

Tripple Slash Error on import

Getting the following errors when trying to import the module:

[0] node_modules/angular2-rest/angular2-rest.d.ts(1,1): error TS2654: Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.
[0] node_modules/angular2-rest/angular2-rest.d.ts(1,1): error TS6053: File 'node_modules/angular2-rest/node_modules/angular2/core.d.ts' not found.
[0] node_modules/angular2-rest/angular2-rest.d.ts(2,1): error TS6053: File 'node_modules/angular2-rest/node_modules/angular2/http.d.ts' not found.
[0] node_modules/angular2-rest/angular2-rest.d.ts(3,1): error TS6053: File 'node_modules/angular2-rest/node_modules/rxjs/Rx.d.ts' not found.

Abandoned Project?

@Paldom,

Is this project now abandoned? If so, is there anyone other than you who has commit access to keep the project going? Or should it be forked and moved forward somewhere else.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.