53

我正在尝试为我的所有 angular 2 http 请求设置基本 url。以下是我的应用程序的基本设置。

class HttpOptions extends BaseRequestOptions {
  url:string = "http://10.7.18.21:8080/api/";
}


bootstrap(AppComponent, [
  HTTP_PROVIDERS,
  provide(RequestOptions, {useClass: HttpOptions})
]);


export class AppComponent {
  users:Array<User>
  constructor(private http: Http) {
    http.get("/users")
      .subscribe(res => this.users = res.json());
  }
}

正如我从配置中所期望的那样,请求没有发送到http://10.7.18.21:8080/api/users 。而是将请求发送到http://localhost:8000/users

如何在 Angular 2 应用程序中设置 http 请求的基本 url?

我正在使用Angular 2.0.0-beta.0

4

9 回答 9

55

对于 Angular 4.3+ 和 @angular/common/http

可以用拦截器来完成

@Injectable()
export class ExampleInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const url = 'http://myurl.com';
    req = req.clone({
      url: url + req.url
    });
    return next.handle(req);
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    ...
  ],
  providers: [
    AppComponent,
    { provide: HTTP_INTERCEPTORS, useClass: ExampleInterceptor, multi: true }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

编辑: Angular 4.3 中引入了 HttpClient 和 HttpInterceptor

于 2017-09-04T12:16:13.303 回答
18

更新:请参阅 Angular 4 的 @vegazz 答案。

对于 Angular 2.2.1,以下内容应作为 web api 基本 url 的前缀并代表更小的占用空间:

import {Request, XHRBackend, XHRConnection} from '@angular/http';

@Injectable()
export class ApiXHRBackend extends XHRBackend {
    createConnection(request: Request): XHRConnection {
        if (request.url.startsWith('/')){
            request.url = 'http://localhost:3000' + request.url;     // prefix base url
        }
        return super.createConnection(request);
    }
}

在 app.module.ts 中注入提供者:

providers: [
    { provide: XHRBackend, useClass: ApiXHRBackend }
  ]

使用示例:

this._http.post('/api/my-route', {foo: 'bar'})
            .map<MyResponse>(res => res.json())

它似乎涵盖了所有方法(GET,PUT,POST,...)

于 2017-02-14T19:36:40.377 回答
11

对于 Angular2 2.2 版(截至 2016 年 12 月)

来自 RC5 的 Angular 标记HTTP_PROVIDERS为已弃用并试图将其移入@NgModule,上述解决方案并不真正适用,因此他们的文档也是如此。我交叉引用了其他几个答案,并找到了实现基本 url 的方法,希望这对其他人有帮助。

基本思想是,我们不是在 bootstrap 中做事情,而是将事情转移到AppModule.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, RequestOptions } from '@angular/http';


import { CustomRequestOptions } from './customrequest.options';

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    BrowserModule,
    HttpModule,
    ...
  ],
  providers: [
    { provide: RequestOptions, useClass: CustomRequestOptions }
  ],
  bootstrap: [ AppComponent ]
})

并将 CustomRequestOptions 移动到单独的可注入服务中

import { Injectable } from '@angular/core';
import { BaseRequestOptions, RequestOptions, RequestOptionsArgs } from '@angular/http';

@Injectable()
export class CustomRequestOptions extends BaseRequestOptions {
  merge(options?:RequestOptionsArgs):RequestOptions {
    options.url = 'http://localhost:9080' + options.url;
    return super.merge(options);
  }
}

编辑 GET 以外的请求方法。

如果您尝试发送 GET 以外的请求类型,则前面的方法无法将 baseurl 注入请求中。这是因为 Angular2 生成了新的,RequestOptions而不是this._defaultOptions其合并方法没有被我们的 CustomRequestOptions 覆盖。(请参阅此处的源代码)。

因此super.merge(...),我没有在 CustomRequestOptions 合并方法的最后一步返回,而是生成了一个新实例CustomRequestOptions以确保以下操作仍然有效。

import { Injectable } from '@angular/core';
import { RequestOptions, RequestOptionsArgs } from '@angular/http';

@Injectable()
export class CustomRequestOptions extends RequestOptions {
  merge(options?: RequestOptionsArgs): RequestOptions {
    if (options !== null && options.url !== null) {
      options.url = 'http://localhost:9080' + options.url;
    }
    let requestOptions = super.merge(options)
    return new CustomRequestOptions({
      method: requestOptions.method,
      url: requestOptions.url,
      search: requestOptions.search,
      headers: requestOptions.headers,
      body: requestOptions.body,
      withCredentials: requestOptions.withCredentials,
      responseType: requestOptions.responseType
    });
  }
}

这也适用于 POST、PUT、DELETE 方法。希望这会有所帮助。

于 2016-12-05T23:42:04.910 回答
7

不同的方法:在 localhost 中运行应用程序的开发过程中,请考虑配置代理

proxy.conf.json

{
   "/api/**": {
      "target": "http://10.7.18.21:8080/",
      "secure": false,
      "logLevel": "debug"
   }
}

更多:链接

于 2017-06-20T07:34:50.023 回答
6

In Angular 2.0.0-beta.6 You can achieve this by overriding 'merge'

import {BaseRequestOptions, RequestOptions, RequestOptionsArgs} from 'angular2/http';

export class ApRequestOptions extends BaseRequestOptions {

  merge(options?:RequestOptionsArgs):RequestOptions {
    options.url = 'http://10.7.18.21:8080/api' + options.url;
    return super.merge(options);
  }

}
于 2016-02-19T13:25:59.473 回答
5

在查看和类的代码源BaseRequestOptions之后:RequestOptionsHttp

url属性似乎对应于默认 URL,但不是 URL 的前缀。

为了实现您的用例,我建议在 http 对象前面放置一个服务,然后注入该服务。像这样的东西:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class HttpClient {
  http: Http;
  urlPrefix: string;

  constructor(http: Http) {
    this.http = http;
    this.urlPrefix = 'http://...';
  }

  get(url) {
    return this.http.get(this.urlPrefix + url);
  }

  post(url, data) {
    return this.http.post(this.urlPrefix + url, data);
  }
}

import {HttpClient} from './http-client';

export classMyComponent {
  constructor(httpClient: HttpClient) {
    this.httpClient = httpClient;
  }

  handleSomething() {
    this.httpClient.post(url, data)
    ).subscribe(...);
  }
}

也就是说,这可能是对 Angular2 本身的贡献;-)

希望它可以帮助你,蒂埃里

于 2015-12-29T18:58:42.383 回答
1
import {LocationStrategy} from 'angular2/router';

constructor(private locationStrategy:LocationStrategy) {
  console.log(locationStrategy.prepareExternalUrl('xxx'));
}

另请参阅https://github.com/angular/angular/blob/1bec4f6c6135d7aaccec7492d70c36e1ceeaeefa/modules/angular2/test/router/path_location_strategy_spec.ts#L88

于 2016-02-19T13:27:32.023 回答
0

对于当前用户,这里是angular 2.4.8中的真正工作示例

是为什么拆分和链接BaseCommonRequestOptionsCommonRequestOptions的代码。

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

于 2017-04-25T15:30:15.287 回答
0

创建一个 .ts 文件

import { Injectable } from '@angular/core';
import {Request, XHRBackend, XHRConnection} from '@angular/http';


    @Injectable()
    export class ApiXHRBackend extends XHRBackend {
    createConnection(request: Request): XHRConnection {
    if (request.url.startsWith('/api')){
    var url=request.url.replace("/api", "");
    request.url = 'http://localhost:8080' + url; // prefix base url
    }
    return super.createConnection(request);
    }

}

然后在 app.module.ts

import { ApiXHRBackend } from './guard/httpintercepter';
import {Request, XHRBackend, XHRConnection} from '@angular/http';

在提供者部分添加提供者

providers: [
{provide: XHRBackend, useClass: ApiXHRBackend }
],

然后在你的 service.ts http 调用中必须像下面的例子

return this._http.post("/api/customerservice/loginvalidation",data)
.map((response: Response) => {
return response;
});

这里 /api 将替换为您的基本 URL http://localhost:8080

更多详情 http://shabeen.in/webschool/how-to-set-angular-2-service-http-base-url/

于 2018-05-17T09:20:31.177 回答