Created
July 25, 2017 16:04
-
-
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"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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