0.1.0 • Published 8 years ago

@angular-util/http v0.1.0

Weekly downloads
1
License
MIT
Repository
github
Last release
8 years ago

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