Embed angular into spring application and access Spring Controllers when running ng serve












1















I plan to set up a Spring-Angular application. I started right away with an Hello World-example to test out how to set up the environment. What I ended up doing:



Creating a Spring-Project and creating an Angular-application within this application. Now I can access Spring-REST-Controllers via the HttpClient Angular Module. (Code example see below).



The advantage: I can use mvn package to pack the Angular- and Spring-parts into one jar and simply deploy it on my tomcat. Sadly, when I run ng serve only the frontend is executed and I cannot access the data in my backend. Is there a way to set up my environment so that I can have the advantage of a one-project-solution and still use ng serve to test it out?



What I tried:



Pack the jar and execute it via terminal (java -jar %jar-file%) and using localhost:8080/hello as a path for my HttpClient instead of a simple /hello. That did not work out sadly.



The code I got so far:



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-Controller:



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>











share|improve this question



























    1















    I plan to set up a Spring-Angular application. I started right away with an Hello World-example to test out how to set up the environment. What I ended up doing:



    Creating a Spring-Project and creating an Angular-application within this application. Now I can access Spring-REST-Controllers via the HttpClient Angular Module. (Code example see below).



    The advantage: I can use mvn package to pack the Angular- and Spring-parts into one jar and simply deploy it on my tomcat. Sadly, when I run ng serve only the frontend is executed and I cannot access the data in my backend. Is there a way to set up my environment so that I can have the advantage of a one-project-solution and still use ng serve to test it out?



    What I tried:



    Pack the jar and execute it via terminal (java -jar %jar-file%) and using localhost:8080/hello as a path for my HttpClient instead of a simple /hello. That did not work out sadly.



    The code I got so far:



    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-Controller:



    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>











    share|improve this question

























      1












      1








      1








      I plan to set up a Spring-Angular application. I started right away with an Hello World-example to test out how to set up the environment. What I ended up doing:



      Creating a Spring-Project and creating an Angular-application within this application. Now I can access Spring-REST-Controllers via the HttpClient Angular Module. (Code example see below).



      The advantage: I can use mvn package to pack the Angular- and Spring-parts into one jar and simply deploy it on my tomcat. Sadly, when I run ng serve only the frontend is executed and I cannot access the data in my backend. Is there a way to set up my environment so that I can have the advantage of a one-project-solution and still use ng serve to test it out?



      What I tried:



      Pack the jar and execute it via terminal (java -jar %jar-file%) and using localhost:8080/hello as a path for my HttpClient instead of a simple /hello. That did not work out sadly.



      The code I got so far:



      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-Controller:



      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>











      share|improve this question














      I plan to set up a Spring-Angular application. I started right away with an Hello World-example to test out how to set up the environment. What I ended up doing:



      Creating a Spring-Project and creating an Angular-application within this application. Now I can access Spring-REST-Controllers via the HttpClient Angular Module. (Code example see below).



      The advantage: I can use mvn package to pack the Angular- and Spring-parts into one jar and simply deploy it on my tomcat. Sadly, when I run ng serve only the frontend is executed and I cannot access the data in my backend. Is there a way to set up my environment so that I can have the advantage of a one-project-solution and still use ng serve to test it out?



      What I tried:



      Pack the jar and execute it via terminal (java -jar %jar-file%) and using localhost:8080/hello as a path for my HttpClient instead of a simple /hello. That did not work out sadly.



      The code I got so far:



      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-Controller:



      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>








      java spring angular maven spring-boot






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 10:27









      RüdigerRüdiger

      213322




      213322
























          1 Answer
          1






          active

          oldest

          votes


















          2














          To do like this



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


          You need to do some proxy configurations.
          Create one proxy-config.json file inside your project in the same directory where package.json is there.



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


          and in package.json inside scripts update "start" command with "start": "ng serve --proxy-config proxy-config.json",
          After that try npm start command to run your project.






          share|improve this answer
























          • This was exactly what I was looking for, thanks for that simple solution!

            – Rüdiger
            Nov 19 '18 at 10:57






          • 1





            welcome @Rüdiger

            – ashish pal
            Nov 19 '18 at 11:00











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372609%2fembed-angular-into-spring-application-and-access-spring-controllers-when-running%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          To do like this



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


          You need to do some proxy configurations.
          Create one proxy-config.json file inside your project in the same directory where package.json is there.



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


          and in package.json inside scripts update "start" command with "start": "ng serve --proxy-config proxy-config.json",
          After that try npm start command to run your project.






          share|improve this answer
























          • This was exactly what I was looking for, thanks for that simple solution!

            – Rüdiger
            Nov 19 '18 at 10:57






          • 1





            welcome @Rüdiger

            – ashish pal
            Nov 19 '18 at 11:00
















          2














          To do like this



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


          You need to do some proxy configurations.
          Create one proxy-config.json file inside your project in the same directory where package.json is there.



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


          and in package.json inside scripts update "start" command with "start": "ng serve --proxy-config proxy-config.json",
          After that try npm start command to run your project.






          share|improve this answer
























          • This was exactly what I was looking for, thanks for that simple solution!

            – Rüdiger
            Nov 19 '18 at 10:57






          • 1





            welcome @Rüdiger

            – ashish pal
            Nov 19 '18 at 11:00














          2












          2








          2







          To do like this



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


          You need to do some proxy configurations.
          Create one proxy-config.json file inside your project in the same directory where package.json is there.



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


          and in package.json inside scripts update "start" command with "start": "ng serve --proxy-config proxy-config.json",
          After that try npm start command to run your project.






          share|improve this answer













          To do like this



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


          You need to do some proxy configurations.
          Create one proxy-config.json file inside your project in the same directory where package.json is there.



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


          and in package.json inside scripts update "start" command with "start": "ng serve --proxy-config proxy-config.json",
          After that try npm start command to run your project.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 10:37









          ashish palashish pal

          31329




          31329













          • This was exactly what I was looking for, thanks for that simple solution!

            – Rüdiger
            Nov 19 '18 at 10:57






          • 1





            welcome @Rüdiger

            – ashish pal
            Nov 19 '18 at 11:00



















          • This was exactly what I was looking for, thanks for that simple solution!

            – Rüdiger
            Nov 19 '18 at 10:57






          • 1





            welcome @Rüdiger

            – ashish pal
            Nov 19 '18 at 11:00

















          This was exactly what I was looking for, thanks for that simple solution!

          – Rüdiger
          Nov 19 '18 at 10:57





          This was exactly what I was looking for, thanks for that simple solution!

          – Rüdiger
          Nov 19 '18 at 10:57




          1




          1





          welcome @Rüdiger

          – ashish pal
          Nov 19 '18 at 11:00





          welcome @Rüdiger

          – ashish pal
          Nov 19 '18 at 11:00


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372609%2fembed-angular-into-spring-application-and-access-spring-controllers-when-running%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)