Created
June 2, 2016 20:13
-
-
Save jondejong/ddde322dbaf2885c46e7c11c96435d73 to your computer and use it in GitHub Desktop.
Angular 2 HttpService example for URL prefixes and auth headers
This file contains 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
@Injectable() | |
export class HttpService { | |
private urlRoot:String; | |
constructor(private _http: Http, | |
private userService:UserService) { | |
this.urlRoot = 'https://api.myapp.com'; | |
if(host == 'localhost'){ | |
this.urlRoot = 'http://localhost:4040'; | |
} | |
} | |
private _createAuthHeaders(): Headers { | |
let headers = new Headers({ | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}); | |
if(this.userService.user) { | |
headers.set('Authorization', this.identityService.user.token); | |
} | |
return headers; | |
} | |
public get(url: string, options?: RequestOptionsArgs) { | |
return this._request(RequestMethod.Get, url, null, options); | |
} | |
public post(url: string, body: string, options?: RequestOptionsArgs) { | |
return this._request(RequestMethod.Post, url, body, options); | |
} | |
public put(url: string, body: string, options?: RequestOptionsArgs) { | |
return this._request(RequestMethod.Put, url, body, options); | |
} | |
public delete(url: string, options?: RequestOptionsArgs) { | |
return this._request(RequestMethod.Delete, url, null, options); | |
} | |
private _request(method: RequestMethod, relativeUrl: string, body?: string, options?: RequestOptionsArgs): Observable<any> { | |
let url = this.urlRoot + relativeUrl; | |
let requestOptions = new RequestOptions(Object.assign({ | |
method: method, | |
url: url, | |
body: body, | |
headers: this._createAuthHeaders() | |
}, options)); | |
return this._http.request(new Request(requestOptions)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment