Skip to content

Instantly share code, notes, and snippets.

@joseluisq
Last active September 26, 2017 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseluisq/3b09f4048b45ee0ab60d2d19c34a2239 to your computer and use it in GitHub Desktop.
Save joseluisq/3b09f4048b45ee0ab60d2d19c34a2239 to your computer and use it in GitHub Desktop.
HTTP service Authorization wrapper + JSON payload
import { Injectable } from '@angular/core'
import { Http, Headers, RequestOptions, Response } from '@angular/http'
import { Observable } from 'rxjs'
import 'rxjs/add/operator/map'
/**
* Usage:
*
* export class MyAuthService {
* constructor (private request: RequestService) {
* request.tokenGetter = (() => sessionStorage.getItem('call_your_token'))
* }
*
* login (username: string, password: string) {
* this.request.post('/auth', { username, password }).map((response: Response) => {
* // handle your data...
* })
* }
* }
*/
@Injectable()
export class RequestService {
tokenGetter: Function
private API_URL = 'http://localhost/api'
private options = new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json'
})
})
constructor (protected $http: Http) {}
baseUrl (url: string) {
return `${this.API_URL}${url}`
}
// Performs a request with `get` http method.
get (url: string, options: RequestOptions = this.options): Observable<Response> {
return this.$http.get(this.baseUrl(url), this.wrapAuthorization(options))
}
// Performs a request with `post` http method.
post (url: string, body: any, options: RequestOptions = this.options): Observable<Response> {
return this.$http.post(this.baseUrl(url), JSON.stringify(body), this.wrapAuthorization(options))
}
// Performs a request with `put` http method.
put (url: string, body: any, options: RequestOptions = this.options): Observable<Response> {
return this.$http.put(this.baseUrl(url), JSON.stringify(body), this.wrapAuthorization(options))
}
// Performs a request with `delete` http method.
delete (url: string, options: RequestOptions = this.options): Observable<Response> {
return this.$http.delete(this.baseUrl(url), this.wrapAuthorization(options))
}
private wrapAuthorization (options: RequestOptions): RequestOptions {
const token: string = this.tokenGetter()
if (token) {
options.headers = options.headers || new Headers()
options.headers.set('Authorization', `Bearer ${token}`)
}
return options
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment