Set base url for angular 2 http requests

TheKojuEffect picture TheKojuEffect · Dec 29, 2015 · Viewed 78.1k times · Source

I am trying to set base url for all my angular 2 http requests. Following is the basic set up for my application.

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

The request is not sent to http://10.7.18.21:8080/api/users as I expected from my configuration. Instead the request is sent to http://localhost:8000/users.

How do I set base url for http request in angular 2 application?

I am using Angular 2.0.0-beta.0.

Answer

vegazz picture vegazz · Sep 4, 2017

For angular 4.3+ and @angular/common/http

It's simple with interceptors

@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 { }

EDIT: HttpClient and HttpInterceptor are introduced in Angular 4.3