我正在使用Spring Boot,Maven和Eclipse开发Angular项目。我想使用“ ng serve”,因此不必每次都构建。因此,我试图使用“ ng serve”从Angular访问网页,并使用REST调用从spring boot获取数据。现在,由于我已经有很多REST调用,所以我不想转到每个文件并将URL更改为http:// localhost:8080 / api / inspection
我想将http:// localhost:8080添加到所有REST调用中。我尝试了以下代码,但仍在调用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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新了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 {
}
Run Code Online (Sandbox Code Playgroud)
您可以查看我之前的问题以获取更多信息: Angular 4 + springboot + Maven + Eclipse-每次都要构建
您可以添加proxy-conf.json
{
"/api": {
"target": "http://localhost:8080",
"secure": false
}
}
Run Code Online (Sandbox Code Playgroud)
并且您的npm start命令将更改为“ ng serve --proxy-config proxy-conf.json -o”
由于Angular在Development Server中运行,因此它将在端口4200中运行,而spring boot在端口8080中运行。当您在本地环境中运行数据时,可以使用proxy conf告诉它将数据传递给其他主机。