Giter Club home page Giter Club logo

angular-http's Introduction

Angular 2 HTTP Utilities

This is the home of angular2 http, a collection of utility classes for http related services. All of these services are collected from different open source projects

Build Status

Getting started

npm install @angular-util/http --save

HttpService class

HttpService is a wrapper around angular's Http with same API as Http. HttpService provides options to intercept request, response and response error. This class is directly lifted from https://github.com/Teradata/covalent.git

To add a desired interceptor, it needs to implement the [HttpInterceptor] interface.

export interface HttpInterceptor {
  onRequest?: (requestOptions: RequestOptionsArgs) => RequestOptionsArgs;
  onResponse?: (response: Response) => Response;
  onResponseError?: (error: Response) => Response;
}

Every method is optional, so you can just implement the ones that are needed.

Example:

import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@covalent/http';

@Injectable()
export class CustomInterceptor implements HttpInterceptor {

  onRequest(requestOptions: RequestOptionsArgs): RequestOptionsArgs {
    ... // do something to requestOptions
    return requestOptions;
  }

  onResponse(response: Response): Response {
    ... // check response status and do something
    return response;
  }

  onResponseError(error: Response): Response {
    ... // check error status and do something
    return error;
  }
}

Also, you need to bootstrap the interceptor providers

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  exports: [
    ...
  ]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        provideHttpService([CustomInterceptor])
      ]
    };
  }
}

After that, just inject [HttpService] and use it for your requests.

Resource class

Resource class provides convinient access to your restful backend service. You will need to extend Resource class to create a service to access your backend. All methods return a Observable

@Injectable()
@ResourceConfig({url: '/api/users'})
export class UserResource extends Resource<User> {
  constructor(http: HttpService) {
    super(http);
  }
}

A simple UserResource defined above will give you access to the following methods.

Default methods (available for free)

Result is always converted to JSON by default, so if your backend service returns JSON you don't have to map result to json.

findOne

Signature: findOne(@Path('id') id: string|number): Observable<T>

Target URL: GET /api/users/{id}

Usage:

userResource.findOne(12)
  .subscribe(
    res => {
      // Do something with success response
    },
    err => {
      // Do something with error
    });

save

Signature: save(body: any): Observable<T>

Target URL: POST /api/users

Usage:

userResource.save(someUserObject)
  .subscribe( ... );

update

Signature: update(id: string|number, body: any): Observable<T>

Target URL: PUT /api/users/{id}

Usage:

userResource.update(12, someUserObject)
  .subscribe( ... );

delete

Signature: delete(id: string|number): Observable<T>

Target URL: DELETE /api/users/{id}

Usage:

userResource.delete(12)
  .subscribe(...);

find

Signature: update(id: string|number, body: any): Observable<T>

This method can be used for query and search screens

Target URL: GET /api/users

Usage:

userResource.find(someQueryObject)
  .subscribe( ... );

Adding extension methods

The code below shows how to extend UserResource with a new method to query roles for a user

@Injectable()
@ResourceConfig({url: '/api/users'})
export class UserResource extends Resource<User> {
  constructor(http: HttpService) {
    super(http);
  }

  @GET('/{id}/roles')
  findRoles(@Path('id') id:number): Observable<List<Role>>> {
    return null; // Return null as actual return is handled by @GET decorator
  }

}

Now you can use this new method as

  userResource.findRoles(12)
    .subscribe( ... );

Decorators on extension method

Decorator type Decorator Description Usage
Request Method @GET(url?: string) This decorator is used for indicating HTTP request method to be used for http request. The url parameter to this decorator is added to base url parameter (specified by @ResourceConfig)
@GET('/{id}/roles')
findRoles(@Path('id') id:number): Observable>> {
  return null; // Return null as actual return is handled by @GET decorator
}
@POST(url?: string)
@PUT(url?: string)
@DELETE(url?: string)
Method Parameter @Path(key: string|number) Used for replacing a URL path placeholder with the method parameter value In this example url path placeholder {id} will be replaced with values of paramater to method call
@GET('/{id}/roles')
findRoles(@Path('id') id:number): Observable>> {
  return null;
}
@Query Used for replacing a URL path placeholder with the method parameter value In this example each key of objects pageRequest and searchParams will be added to the URL as parameters.
@GET('/roles')
find(@Query pageRequest?: PageRequest, @Query searchParams?: any): Observable> {
  return null;
}
@Body The indicated parameter will be sent as body of the request In this example roles object will be stringified and sent and body of the http request.
@POST('/roles')
addRoles(@Body roles: any): Observable {
  return null;
}
@Header The indicated parameter will be sent as header of the request In this example a request header secretKey with value as key will be sent with the http request.
@POST('/activate')
activate(@Header('secretKey') key: string): Observable {
  return null;
}

angular-http's People

Contributors

mmrath avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

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.