Skip to content

Instantly share code, notes, and snippets.

@cm0s
Last active June 9, 2016 20:46
Show Gist options
  • Save cm0s/878db99efb9b11b13d95a524c7bb6c6f to your computer and use it in GitHub Desktop.
Save cm0s/878db99efb9b11b13d95a524c7bb6c6f to your computer and use it in GitHub Desktop.
Simple Rest Service for Angular 2
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {RestService} from '../../../common-ng2/src/application/services/rest.service';
import * as moment from 'moment/moment';
@Injectable()
export class EassessmentService {
constructor(private rest:RestService) {
this.rest = rest;
}
public getAll():Observable<Eassessment[]> {
return this.rest.get('eassessments').map(data=> {
return <Eassessment[]> Eassessment.create(data);
});
}
public get(id:string):Observable<Eassessment> {
return this.rest.get('eassessments/' + id).map(data=> {
return <Eassessment> Eassessment.create(data);
});
}
//Other method save, create, etc. can be added
}
import {UploadedFile} from '../../../common-ng2/src/directives/upload/upload.component';
import {Person} from './person';
export enum FileLocation {
db, url
}
export class Eassessment {
public static create(data:any):Eassessment|Array<Eassessment> {
if (data instanceof Array) {
let array:Array<Eassessment> = [];
for (let item of <Array<Eassessment>>data) {
let eassessment = new Eassessment(item.id, item.name, item.description, item.dbFile, item.urlFile,
item.creator, item.startDate, item.activeFile);
array.push(eassessment);
}
return array;
} else {
return new Eassessment(data.id, data.name, data.description, data.dbFile, data.urlFile, data.creator,
data.startDate, data.activeFile);
}
}
constructor(public id?:number,
public name?:string,
public description?:string,
public dbFile?:UploadedFile,
public urlFile?:string,
public creator?:Person,
public startDate?:any,
public activeFile?:string) {
this.creator = new Person();
this.activeFile = FileLocation[FileLocation.db];
}
isActiveFileDbFile():boolean {
return this.activeFile === FileLocation[FileLocation.db];
}
isActiveFileUrlFile():boolean {
return this.activeFile === FileLocation[FileLocation.url];
}
}
import {Injectable, Inject, OpaqueToken, Provider, provide} from '@angular/core';
import {Http, Response, Headers, RequestOptions, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {FlashService} from './flash.service';
import {Subject} from 'rxjs/Subject';
import 'rxjs/Rx';
/**
* Interface for API configuration
*/
export interface IConfig {
root:string;
}
@Injectable()
export class RestService {
public static CONFIG:OpaqueToken = new OpaqueToken('Rest config context');
private http:Http = null;
private config:IConfig = null;
private flash:FlashService = null;
private _error:Subject<Response> = Subject.create();
public static provideConfig(config:IConfig):Provider {
return provide(RestService.CONFIG, {useValue: config});
}
public static config(base:string):IConfig {
return {
root: base
};
}
constructor(http:Http, @Inject(RestService.CONFIG) config:IConfig, flash:FlashService) {
this.http = http;
this.config = config;
this.flash = flash;
}
public get root():string {
return this.config.root;
}
public get error():Observable<Response> {
return this._error;
}
get(url:string, args?:{ [id:string]:any; }) {
let options:RequestOptions = null;
if (args) {
var params = new URLSearchParams();
var property:string;
for (property in args) {
if (args.hasOwnProperty(property)) {
let value:any = args[property];
params.set(property, value);
}
}
options = new RequestOptions({search: params});
}
return this.http.get(this.config.root + url, options)
.do(response => this.flash.onResponse(response))
.map(response => response.json())
.catch(response => this.handleError(response));
}
post(url:string, content:any = null) {
let body = JSON.stringify(content);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(this.config.root + url, body, options)
.do(response=>this.flash.onResponse(response))
.map(response => response.json())
.catch(response => this.handleError(response));
}
delete(url:string) {
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.delete(this.config.root + url, options)
.do(response=>this.flash.onResponse(response))
.map(response => response.json())
.catch(response => this.handleError(response));
}
put(url:string, content:any) {
let body = JSON.stringify(content);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.put(this.config.root + url, body, options)
.do(response=>this.flash.onResponse(response))
.map(response => response.json())
.catch(response => this.handleError(response));
}
rootApiUrl():string {
return this.config.root;
}
private handleError(error:Response) {
this.flash.onResponse(error);
this._error.next(error);
return Observable.throw(error.json().error || 'Server error');
}
}
@cm0s
Copy link
Author

cm0s commented Jun 9, 2016

We have a RestService which handles XHR requests with the angular2 Http service. A model is created here it's named eassessment. This model has a factory method named create which is used to create a new instance of the Eassessment class with a javascript object. Object or array of objects can be proceeded.
For each model we have, we create a corresponding service "EassessmentService " which uses "RestService" to send an XHR, retrieves a javascript object or array of object and convert it into an instance of Eassessment or Array of Eassessment before returning it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment