Angular 2在post请求中动态更改基本URL [英] Angular 2 dynamically change base url in post requests

查看:296
本文介绍了Angular 2在post请求中动态更改基本URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular2 / TypeScript应用程序中有角度服务,它们不知道http服务的位置 - 显然需要什么。

I have angular services in Angular2/TypeScript application which are not aware of http services location - what is obviously required.

出于测试目的,我需要运行我的具有多个目标的TypeScript应用程序 - 它可以是localhost(用于测试)或云环境。目标是通过源代码中的单行更改将所有请求从一个地址切换到另一个地址。
可接受的解决方案不应要求在所有角度服务中添加目标位置作为常量值。

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.

我找到了一个很好的例子如何做到这一点Angular 2 - 动态查找要用于的基本网址http请求(服务)

I found a good example how to do that Angular 2 - Dynamically find base url to use in the http requests (services)

使用Angular2的2.0.0-beta.6版本,您可以覆盖合并方法

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 })
]);

但是

它适用于GET请求,但是对POST请求不起作用 - POST中的基本URL没有被触及(浏览器向JavaScript主机服务器发送请求而不是所需的http目标)。

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).

如何动态更改Angular 2中POST请求的基本URL地址?

How to dynamically change base url address for POST requests in Angular 2?

推荐答案

尝试这种方式

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;
    }
}

bootstrap(AppComponent, [HTTP_PROVIDERS,
    // < RC.4
    provide(RequestOptions, { useClass: CustomRequestOptions }),
    // >= RC.4
    { provide: RequestOptions, useClass: CustomRequestOptions }
]);

这篇关于Angular 2在post请求中动态更改基本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆