https://hboylan.github.io/ng2-http/demo
Angular2 HttpModule wrapper with decorators and interceptors
Based the source code from this repo.
Install through yarn:
yarn add ng2-http
Install through npm:
npm install --save ng2-http
Then use it in your app like so:
// demo.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {RESTModule} from 'ng2-http';
import {Demo} from './demo.component';
import {DemoService} from './demo.service';
@NgModule({
declarations: [Demo],
imports: [BrowserModule, RESTModule],
bootstrap: [Demo],
providers: [DemoService]
})
export class DemoModule {}
// demo.service.ts
import {Injectable} from '@angular/core';
import {Http, Request, Response} from '@angular/http';
import {RESTClient, BaseUrl, DefaultHeaders, GET, POST, Body, Query, Produces} from 'ng2-http';
import {Observable} from 'rxjs/Observable';
@Injectable()
@BaseUrl('https://jsonplaceholder.typicode.com')
@DefaultHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
export class DemoService extends RESTClient {
constructor(protected http: Http) {
super(http);
// Optional
this.withCredentials = true;
}
protected requestInterceptor(req: Request): Observable<Request> {
return super.requestInterceptor(req); // wraps Observable.of
}
protected responseInterceptor(res: Observable<Response>): Observable<Response> {
return res;
}
@POST('/posts')
@Produces<Post>()
public createPost(@Body post: Post): Observable<Post> {
return null;
}
@GET('/posts')
@Produces<Post[]>()
public getPosts(@Query('userId') userId?: number): Observable<Post[]> {
return null;
}
}
export class Post {
constructor(
public userId: number,
public title: string,
public body: string,
public id?: number
) {}
}
// demo.component.ts
import {Component, Input} from '@angular/core';
import {DemoService, Post} from './demo.service';
@Component(...)
export class Demo {
@Input() public demoPost: Post = new Post(1, 'Demo Title', 'Demo Body');
@Input() public demoList: Post[] = [];
constructor(public demoService: DemoService) {
this.getPosts();
}
createPost() {
this.demoService.createPost(this.demoPost);
}
getPosts() {
this.demoService.getPosts().subscribe(posts => {
this.demoList = posts;
});
}
}
All documentation is auto-generated from the source via typedoc and can be viewed here: https://hboylan.github.io/ng2-http/docs/
- Install Node.js and NPM (should come with)
- Install local dev dependencies:
npm install
while current directory is this repo
Run npm start
to start a development server on port 8000 with auto reload + tests.
Run npm test
to run tests once or npm run test:watch
to continually run tests.
- Bump the version in package.json (experts only)
npm run release
MIT