Spring boot, maven, AngularJS 2, typescript and live reload

I am in a study phase for an application development. The server-side development has already started, with Spring boot and Maven. Now, I am studying the possible options to develop the client-side.

I’d like to use Angular 2 (I know it’s still in alpha), but I’m really hesitating between its javascript and typescript version. I know the live reload with javascript version should work well with maven spring-boot run (in theory), and this is a great help for productivity. I was wondering if there was a way to have the live reload for typescript version of Angular too. Has anyone managed to implement it in its own project? If yes, how did you do?

I have not found any doc about this on maven-typescript-plugin

The build system will be Maven for client side too.

EDIT: Is there an easy way for typescript debugging, or is it a pain?

Angular2 Response not casting

I am making a call to my backend server (Spring Boot) and it returns a list of objects Foo.

However, when I go to list my objects in *ngFor it doesn’t iterate at all. I know my server is return a list of two objects, as I have debugged it, and the response back is an array of two objects. I think I am missing a silly step, and any help is greatly appreciated.

foo.ts

name: string;
id: number;
description: string;

list-foo.service.ts

@Injectable
export class ListFooService
constructor(private _http: Http) {}
private _getFooUrl = '/api/foos/foos';

getFoos() {
    return this._http.get(this._getFooUrl)
        .map(res => <Foo[]> res.json())
        .do(data => console.log(data))
}

And this I know returns an array of two objects, as show in the last step of my chain.

@Component({
selector: 'foo-component',
templateUrl: 'app/templates/foo.component.html'
})


export class FooComponent implements OnInit {

constructor(private _listFooService:ListFooService) {
}

foos:Foo[];
errorMessage:string;

ngOnInit() {
    this.getFoos();
}

getFoos() {
    this._listFooService.getFoos()
        .subscribe(
            foos => {this.foos = foos; console.log("Foos"); console.log(this.foos)},
            error => this.errorMessage = <any>error);
    }
}

and my foo.component.html

<ul>
<li *ngFor="#foo of foos">
    {{foo.name}}
</li>
</ul>
test

I get nothing to show, except for test (which is outside of my for block)

and if it helps here is the backend

FooController.java

@RequestMapping("/connectors")
public @ResponseBody List<Foo> getFooList()
{
    return fooDAO.getAllFoos(); //this works
}

and Foo.java

private String name;
private int id;
private String description;
//getters and setters

and the <head> in my html file

<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.min.js"></script>
<script src="node_modules/angular2/bundles/router.min.js"></script>
<script src="node_modules/angular2/bundles/upgrade.js"></script>
<script src="node_modules/angular2/bundles/http.min.js"></script>

And the JSON response back from the server is

[
 {
  "name": "Foo",
  "id": 1,
  "description": "FooBar"
 },
 {
   "name": "Foo2",
   "id": 2,
   "description": "FooBar2"
 }
]

How to use webpack combine angular2 with existing spring boot server

I want the existing spring boot gateway as the backend server, instead of the angular 2 .

that is i want the angular2 combines to the spring gateway .

Assume :

the angular 2 webpack-dev-server on port 8090 , and there is a
page index.html

spring boot gateway on port 8080: and all the api .

I want to open

localhost:8080 

to see the angular2 index.html ,

how to implement ?

Insert Image to database using typescript (angular2) and spring boot (spring data)

I start by presenting my client side the service

    addImage (url: string, params: string[], files: File[]): Observable {
                return Observable.create(observer => {
                    let formData: FormData = new FormData(),
                        xhr: XMLHttpRequest = new XMLHttpRequest();

                    for (let i = 0; i < files.length; i++) {
                        formData.append("uploads[]", files[i], file

s[i].name);
                }

                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            observer.next(JSON.parse(xhr.response));
                            observer.complete();
                        } else {
                            observer.error(xhr.response);
                        }
                    }
                };

                xhr.upload.onprogress = (event) => {
                    this.progress = Math.round(event.loaded / event.total * 100);

                    this.progressObserver.next(this.progress);
                };

                xhr.open('POST', url, true);
                xhr.send(formData);
            });

    }

then this is my html code

<input type="file" (change)="uploadImage($event)"/>

where I call this method from my component

uploadImage(event) {
        var files = event.srcElement.files;
        console.log(files);
        this._serviceSection.addImage('http://localhost:8080/template/img', [], files).subscribe(() => {
            console.log('sent');
        });
    }

and in my service side

this is a method from my controller

@RequestMapping(value = "/img", method = RequestMethod.POST)
    public void getFileContents(@RequestParam MultipartFile file) {
        System.out.println("++++++++++++++++++++++++++++++++++++++++ " +file.getOriginalFilename());
    }

in a first time a try just to show a fileName but I get this error

enter image description here

How to setup structure with SpringBoot and Angular2?

I’m trying to use Angular2 with Springboot, but I can’t set them together.

I first started a springboot project, and then tried to follow the Angular 2 Tour of Heroes by johnpapa and run npm install.

The structure looks like below:

Structure

I have the /app folder, and the .js are compiled to resources/static/app/js.

Problems:

1) The folder resources/static/node_modules/ has lots of files. So when running bootRun, it gets really slow and sometimes can’t even refresh the files. I believe I shouldn’t put the node_modules there, but not sure..

2) npm install puts the files in ./node_modules so currently I copied them to static folder. Should I just build the node_modules to static?

3) My structure looks hacky.. what is the best way to do it ?

How to set this structure? Also, please let me know if I should start using grunt/gulp or some other tool to make this easier.

Ps.: In case anyone is interested in the johnpapa’s guide: johnpapa’s angular2 guide

Exclude Angluar2 route from Spring Web MVC application

I have a spring-boot application that has a few views set up. I also have bundled an Angular2 app. When I load the Angular2 app, all works fine, however, when I try to deep link to a route within the application, Spring MVC is intercepting the call, failing to find an associated view and returning the error page.

http://localhost:8080/index.html will load the Angular2 application which then re-writes the URL to be just http://localhost:8080/. If I then navigate to the route I want e.g. http://localhost:8080/invite/12345, then the route loads and works as expected. Hitting http://localhost:8080/invite/12345 directly returns the standard Spring MVC error page.

However, if I run the Angular2 app as a standalone application (not served up by spring-boot), then hitting that link directly works as expected. it loads the index.html, fires the route and shows me the data I want.

How can I, via Java configuration, tell Spring to ignore the /invite/** path (and other paths too as my Angular2 app grows) so I can deep-link to routes within my Angular2 application. Here’s the current Java configuration:

@SpringBootApplication
@EnableResourceServer
public class AuthserverApplication extends WebMvcAutoConfigurationAdapter {

    public static void main(String[] args) {
        SpringApplication.run(AuthserverApplication.class, args);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/oauth/confirm_access").setViewName("authorize");
        registry.addViewController("/success").setViewName("success");
    }

    @Bean
    public ViewResolver getViewResolver() {
        final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setSuffix(".html");
        return resolver;
    }
}

This project is inheriting from spring-boot 1.3.3.RELEASE:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>

Whitelabel Error Page after refresh

I have Spring Boot Application (backend) and for the Frontend I am using the Angular 2 Single Page Application.

Whenever I navigate to a route for example: localhost:8080/getAccounts and do after the navigation a refresh I get the Whitelabel Error Page. If I am at the root localhost:8080 I works fine. The problem only occurs in the sub links.

Returning (use the return/back button) to the previous page also works fine. Just the refresh.

I also can not call direct the link: localhost:8080/getAccounts. First I have to go to Home (localhost:8080) an call the page throug sub navigation bar.

Does anybody had the same problem? What excalty I do have to change. My Code:

Main.ts

import {bootstrap} from '@angular/platform-browser-dynamic';
import {AppComponent} from './components/app.component';
import {HTTP_PROVIDERS};
import {enableProdMode} from '@angular/core';

enableProdMode();
bootstrap(AppComponent, [HTTP_PROVIDERS]);

app.comonent:

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

import { Http } from '@angular/http';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';

import { HomeComponent } from './home.component';
import { UserSearchComponent} from './webUserProfiles.component';
import { UserDetailViewComponent} from './webUserProfileView.component'; 

import { HTTPService } from '../service/http.service';


@Component({
  selector: 'app-content',
  templateUrl: './app/templates/app.component.html',
  directives: [ROUTER_DIRECTIVES, AccessErrorComponent],
  providers: [
    ROUTER_PROVIDERS,
    HTTPService
  ]
})

@RouteConfig([
  {
    path: '/',
    name: 'HomeComponent,
    useAsDefault: true
  },
  {
    path: '/user',
    name: 'UserSearch',
    component: UserSearchComponent,
  },
  {
    path: '/user/:id',
    name: 'UserDetailView',
    component: UserDetailViewComponent,
  }
])

export class AppComponent implements OnInit {
    constructor (
    ) { } 
}
}

Thanks in advance

SockJS over stomp using angular2 and spring boot

I want to implement a websocket inside my projet to do something as notifications

this is my configuration web socket in my projet spring boot

 @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/hello").setAllowedOrigins("*").withSockJS();
    }

and in my controller I have this method :

@MessageMapping("/hello")
    @SendTo("/topic/templatesWS")
    public void TemplatesWebSocket() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("calling juste");
    }

and in my client side in my page index.html I added this

<script src="//cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js"></script>

and in my component angular2 I’m using this

declare let SockJS;
        declare let Stomp;


        var socket = new SockJS('http://localhost:8080/hello');
        socket.ono
        var stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('http://localhost:8080/template/topic/templatesWS', function(greeting) {
                console.log("from from", greeting);
            });
        }, function (err) {
            console.log('err', err);
        });

How can I call the method TemplatesWebSocket()

enter image description here