Skip to content

Instantly share code, notes, and snippets.

@genuinefafa
Created July 25, 2017 16:04
Show Gist options
  • Save genuinefafa/4b331c280e61bd95f46556c86ce1e944 to your computer and use it in GitHub Desktop.
Save genuinefafa/4b331c280e61bd95f46556c86ce1e944 to your computer and use it in GitHub Desktop.
based on the example from Jonathan Serra using ngx-resource as of "^3.2.4"
// based on http://blog.slals.net/programming/2017/01/12/angular2-a-rest-client-interface.html
import { Http, Request } from '@angular/http';
import { ResourceCRUD, ResourceActionBase } from 'ngx-resource';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
export class RestClientCRUD<TQuery, TShort, TFull> extends ResourceCRUD<TQuery, TShort, TFull> {
$getHeaders(methodOptions?: any): any {
const headers: any = {};
if (methodOptions.auth) {
headers.Authorization = localStorage.get('token');
}
return headers;
}
$responseInterceptor(observable: Observable<any>, request: Request, methodOptions?: any): Observable<any> {
return Observable.create((subscriber: Subscriber<any>) => {
observable.subscribe(
(res: Response) => {
if (res.headers) {
const newToken: string = res.headers.get('Authorization');
if (newToken) {
localStorage.setItem('token', newToken);
}
}
const body = (<any>res)._body;
subscriber.next(body ? res.json() : null);
},
(error: Response) => {
// I also made a layer to parse errors
subscriber.error(new Error(error.statusText));
},
() => subscriber.complete()
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment