Angular 4.0:为REST调用设置基本URL

时间:2018-04-19 19:25:08

标签: angular

我正在开发一个带有spring boot,maven和eclipse的Angular项目。我想使用“ng serve”,所以我不必每次都建立。所以我试图使用'ng serve'从Angular访问网页,并使用REST调用从spring boot获取数据。既然我已经有很多REST调用,我不想去每个文件并将网址更改为http://localhost:8080/api/inspection

我想在所有REST调用中添加http://localhost:8080。我尝试了以下代码,但它仍在调用http://localhost 4200 / api / inspection

创建了IqsInterceptor.ts:

import {  Injectable, } from '@angular/core';
import {  HttpRequest,  HttpHandler,  HttpEvent,  HttpInterceptor} from '@angular/common/http';
import {  Observable} from 'rxjs/Observable';

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

更新了app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AlertService} from './alert/alert.service';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import { Injectable } from '@angular/core';
import { HttpClientModule, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';

import {IqsInterceptor} from './IqsInterceptor';

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        FormsModule,
        HttpModule,
        AppRoutingModule
    ],
    providers: [
        AppComponent,
        { provide: HTTP_INTERCEPTORS, useClass: IqsInterceptor, multi: true }

    ],
    declarations: [
        AppComponent,
        . . . Other components
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

您可以查看我之前的问题以获取更多信息: Angular 4 + springboot + Maven + Eclipse - Have to build everytime

1 个答案:

答案 0 :(得分:4)

您可以添加proxy-conf.json

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false
  }

}

您的npm start命令将更改为&#34; ng serve --proxy-config proxy-conf.json -o&#34;

由于Angular在开发服务器中运行,它将在端口4200中运行,并且Spring引导在端口8080中运行。您可以使用代理配置文件告诉它在您在本地运行时将数据传递到其他主机环境。