Вставить угловой в приложение Spring и получить доступ к Spring Controllers при запуске нг подачи - PullRequest
0 голосов
/ 19 ноября 2018

Я планирую настроить приложение Spring-Angular. Я сразу начал с примера Hello World, чтобы проверить, как настроить среду. Что я в итоге сделал:

Создание Spring-Project и создание Angular-приложения в этом приложении. Теперь я могу получить доступ к Spring-REST-Controllers через HttpClient угловой модуль. (Пример кода см. Ниже).

Преимущество: я могу использовать пакет mvn, чтобы упаковать детали Angular и Spring в одну банку и просто развернуть их на своем коте. К сожалению, когда я запускаю ng serve, выполняется только внешний интерфейс, и я не могу получить доступ к данным в своем бэкэнде. Есть ли способ настроить мою среду так, чтобы я мог использовать преимущество одного проекта и при этом использовать ng serve для его тестирования?

Что я пробовал:

Упакуйте банку и выполните ее через терминал (java -jar %jar-file%), используя localhost:8080/hello в качестве пути для моего HttpClient вместо простого /hello. К сожалению, это не сработало.

Код, который я получил до сих пор:

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'HelloWorld';
  message: string;

  constructor(private http : HttpClient) {}

  ngOnInit() : void {
    //this is where I tried to use localhost:8080/hello instead
    this.http.get('/hello').subscribe( data => {
      console.log('DATA', data);
      this.message = data['message'];
    });
  }
}

Rest-контроллер:

package com.example.helloWorld.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String sayHello() {
        return "{\"message\": \"Hello, World!\"}";
    }

}

pom.xml http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

<groupId>com.example</groupId>
<artifactId>helloWorld</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>helloWorld</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.restdocs</groupId>
        <artifactId>spring-restdocs-mockmvc</artifactId>
        <scope>test</scope>
    </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-autoconfigure</artifactId>
  <version>2.1.0.RELEASE</version>
  <type>jar</type>
 </dependency>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
</dependencies>

<build>
    <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>exec-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>validate</phase>
                                <goals>
                                    <goal>exec</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <executable>ng</executable>
                            <workingDirectory>src/main/ui</workingDirectory>
                            <arguments>
                                <argument>build</argument>
                            </arguments>
                        </configuration>
                    </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

1 Ответ

0 голосов
/ 19 ноября 2018

Чтобы сделать это

this.http.get('/hello').subscribe( data => {
      console.log('DATA', data);
      this.message = data['message'];
    });

Вам необходимо выполнить некоторые настройки прокси.Создайте один файл proxy-config.json внутри вашего проекта в том же каталоге, где находится package.json.

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

и в package.json внутри scripts обновите команду "start" с помощью "start": "ng serve --proxy-config proxy-config.json", После этого попробуйтеnpm start команда для запуска вашего проекта.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...