Created
April 25, 2017 15:08
-
-
Save enif-lee/48139b9874d4287d778a03113f40031f to your computer and use it in GitHub Desktop.
how to set base url in angular
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
import { BaseRequestOptions, Headers, RequestOptions, RequestOptionsArgs } from '@angular/http'; | |
import { Injectable } from '@angular/core'; | |
@Injectable() | |
export class BaseCommonRequestOptions extends BaseRequestOptions { | |
merge(options?: RequestOptionsArgs): RequestOptions { | |
return new CommonRequestOptions(super.merge(extracted(options))); | |
} | |
} | |
/** | |
* for inner merge when using post put patch delete...others method | |
*/ | |
export class CommonRequestOptions extends RequestOptions { | |
merge(options?: RequestOptionsArgs): RequestOptions { | |
return new RequestOptions(super.merge(extracted(options))); | |
} | |
} | |
/** | |
* inject default values | |
* | |
* @param options | |
* @returns {RequestOptionsArgs} | |
*/ | |
export function extracted(options: RequestOptionsArgs) { | |
console.log(options); | |
if (!validUrl(options.url)) { | |
options.url = 'http://localhost:3000' + (options.url ? options.url : ""); | |
} | |
// use default header application/json, if content-type header was empty. | |
if (options.headers != null) { | |
let contentType = options.headers.get('content-type'); | |
if (contentType == null || contentType == '') { | |
options.headers.append('content-type', 'application/json'); | |
} | |
} else { | |
options.headers = new Headers({ 'content-type': 'application/json' }); | |
} | |
return options; | |
} | |
/** | |
* validate url | |
* | |
* @param url | |
* @returns {boolean} | |
*/ | |
export function validUrl(url: string) { | |
return /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment