I have angular services in Angular2/TypeScript application which are not aware of http services location - what is obviously required.
For testing purposes, I need to run my TypeScript application with more than one target - it could be either localhost (for testing) or cloud environment. The goal is to switch all request from one address to the other one with one-line change in source code. The acceptable solution should not require to add target location as constants value in all angular services.
I found a good example how to do that Angular 2 - Dynamically find base url to use in the http requests (services)
With version 2.0.0-beta.6 of Angular2, you can override the merge method
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';
export class CustomRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'http://192.123.24.2:8080' + options.url;
return super.merge(options);
}
}
You can register this class this way:
bootstrap(AppComponent, [HTTP_PROVIDERS,
provide(BaseRequestOptions, { useClass: CustomRequestOptions })
]);
But
It works for GET requests, but is does not work for POST requests - base url in POST has not been touched (browser sends request to JavaScript host server instead to required http target).
How to dynamically change base url address for POST requests in Angular 2?
Try this way
import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';
export class CustomRequestOptions extends BaseRequestOptions {
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = 'http://192.123.24.2:8080' + options.url;
var result = super.merge(options);
result.merge = this.merge;
return result;
}
}
and
bootstrap(AppComponent, [HTTP_PROVIDERS,
// < RC.4
provide(RequestOptions, { useClass: CustomRequestOptions }),
// >= RC.4
{ provide: RequestOptions, useClass: CustomRequestOptions }
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With