【问题标题】:Angular 4.0: Set base url for REST callsAngular 4.0:为 REST 调用设置基本 url
【发布时间】:2018-04-19 19:25:08
【问题描述】:

我正在使用 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);
  }
}

更新了 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

【问题讨论】:

    标签: angular


    【解决方案1】:

    你可以添加一个proxy-conf.json

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

    您的 npm start 命令将更改为“ng serve --proxy-config proxy-conf.json -o

    由于 Angular 在开发服务器中运行,它将在端口 4200 中运行,而 Spring Boot 在端口 8080 中运行。您可以使用代理 conf 告诉它在本地运行时将数据传递到不同的主机环境。

    【讨论】:

    • proxy-conf.json 的路径是什么?
    • package.json所在的同级
    猜你喜欢
    • 2016-04-03
    • 2019-09-06
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2013-07-20
    相关资源
    最近更新 更多