Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dynamically change base url in post requests

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?

like image 555
Sławomir Siudek Avatar asked Feb 28 '16 19:02

Sławomir Siudek


1 Answers

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 }
]);
like image 115
Luca Avatar answered Oct 23 '22 03:10

Luca