Skip to content

Repository files navigation

npm versionGitHub versionGitHub forksGitHub starsGitHub issuesGitHub pull requestslicense

angular-async-http

Angular 4 Async HTTP client in typescript with promises, interceptors, and timeouts. Note: Production Ready! (Well tested)

Installation

npm install angular-async-http --save

Example

import{Http,Request,Response}from'@angular/http';import{Observable}from'rxjs/Observable';import{HttpClient,RestClient,Client,GET,PUT,POST,DELETE,Headers,Path,Body,Query,Produces,MediaType}from'angular-async-http';import{Todo}from'./models/Todo';import{SessionFactory}from'./sessionFactory';
@Injectable()
@Client({serviceId: 'todo-service',baseUrl: 'http://localhost:3000/api/',headers: {'content-type': 'application/json'}})exportclassTodoClientextendsRestClient{constructor(http:Http){super(<HttpClient>http);}protectedrequestInterceptor(req: Request):void{if(SessionFactory.getInstance().isAuthenticated){req.headers.append('jwt',SessionFactory.getInstance().credentials.jwt);}}protectedresponseInterceptor(res: Observable<Response>): Observable<any>{// do anything with responsesreturnres;}
@Get("todo/")
@Timeout(2000)//In milliseconds
@Produces(MediaType.JSON)publicgetTodos( @Query("page")page:number, @Query("size",{default: 20})size?:number, @Query("sort")sort?: string): Observable<Todo[]>{returnnull;};
@Get("todo/{id}")
@Timeout(2000)//In milliseconds
@Map(resp=>newTodo(resp.json()))publicgetTodoById( @Path("id")id: number): Observable<Todo>{returnnull;};
@Post("todo")
@Timeout(2000)//In milliseconds
@Headers({'content-type': 'application/json'})publicpostTodo( @Bodytodo: Todo): Observable<Response>{returnnull;};
@Put("todo/{id}")
@Timeout(2000)//In millisecondspublicputTodoById( @Path("id")id: string, @Bodytodo: Todo): Observable<Response>{returnnull;};
@Delete("todo/{id}")
@Timeout(2000)//In millisecondspublicdeleteTodoById( @Path("id")id: string): Observable<Response>{returnnull;};}

Using it in your component

app.module.ts

@NgModule({declarations: [AppComponent],imports: [HttpModule],providers: [TodoClient],bootstrap: [AppComponent]})exportclassAppModule{}

todo.component.ts

// You need some or all of the following rxjs imports for Promise and Observable.import'rxjs/add/observable/defer';import'rxjs/add/observable/throw';import'rxjs/add/operator/map';import'rxjs/add/operator/timeout';import'rxjs/add/operator/toPromise';import{Observable}from'rxjs/Observable';
@Component({selector: 'to-do',})exportclassToDoCmp{constructor(privatetodoClient: TodoClient){}// Use todoClient.sampleUsage(){this.todoClient.getTodos(/* page */1).subscribe(data=>{console.log(data)})}// Another example, using Promises.sampleUsage2(){this.todoClient.getTodos(/* page */1).toPromise().then((response: Response)=>console.log(response.json())).catch(this.handleError);})}privatehandleError(error: any): Promise<any>{
console.error('An error occurred',error);console.log('ERROR');returnPromise.reject(error.message||error);}}

API Docs

RestClient

Methods:

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

Class decorators:

  • @Client(args:{serviceId?: string, baseUrl?: string, headers?: any})

Method decorators:

  • @Get(url: String)
  • @Post(url: String)
  • @Put(url: String)
  • @Patch(url: String)
  • @Delete(url: String)
  • @Head(url: String)
  • @Headers(headers: Object)
  • @Map(mapper:(resp : any)=>any)
  • @OnEmit(emitter:(resp : Observable<any>)=>Observable<any>)
  • @Timeout(timeout: number)

Parameter decorators:

  • @Path(name: string, value?:any|{value?:any})
  • @Query(name: string, value?:any|{value?:any,format?:string})
  • @Header(name: string, value?:any|{value?:any,format?:string})
  • @Body

Collection Format

Determines the format of the array if type array is used. (used for @Query and @Header) Possible values are:

  • Format.CSV - comma separated values foo,bar.
  • Format.SSV - space separated values foo bar.
  • Format.TSV - tab separated values foo\tbar.
  • Format.PIPES - pipe separated values foo|bar.
  • Format.MULTI - corresponds to multiple parameter instances instead of multiple values for a single instance foo=bar&foo=baz. This is valid only for parameters in "query" or "formData".

Default value is Format.CSV.

Contributors

Brought to you by many contributors, including:

TrustPortal Solutions Ltd http://trustportal.org
Yavin Five
deblockt
Dmitry-Gorbenko
Maxxton Group http://www.maxxton.com
Domonkos Pal : Paldom
Discountrobot
TN-Kirontech
LeFinc
mmrath http://www.mmrath.com
steven166
Mayur Patel : mayur-novus

License

MIT

About

Angular 4 Async HTTP client in typescript with promises, interceptors, and timeouts.

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages