0
1

More than 3 years have passed since last update.

Spring Boot Gradle + Angularの連携

Last updated at Posted at 2021-03-31

Spring Boot側からデータを返却しAngularで受け取り、画面に表示させる

Spring Boot

DemoController.java
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    @Autowired
    DemoService demoService;

    @RequestMapping("api/data")
    public String getString() {
        return demoService.getString();
    }
}
DemoService.java
package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class DemoService {
    public String getString() {
        return "[{\"title\":\"app\"}]";
    }
}
WebMvcConfigurer.java
package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins("*")
        .allowedMethods("*");
    }
}

・Controller
  @RequestMapping("api/data")でAngular側からのリクエストに対してのURLを指定

・Service
  返却する値をJson形式で設定
  今回は文字列を指定

・Config
  CORSの設定(Cross-Origin Resource Sharing)
  Webページでは同一生成元ポリシーによって生成したドメイン以外へのHTTPリクエストができないみたいで
  それを可能にするためのCORSでの設定。

Angular

app.component.ts
import { Component,OnInit } from '@angular/core';
import { AppService } from './app.service'

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

  constructor(
    private appService: AppService,
  ) { }

  ngOnInit() {
    this.title = "my-app";
  }

  onClick() {
    this.getString(); 
  }

  getString():void {
    this.appService.getString()
      .subscribe(response=>{
        this.title = response[0].title;
      });
  }
}
app.service.ts
import { Injectable }    from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Item } from './item';

@Injectable({providedIn: 'root'})
export class AppService {
  private url = 'http://localhost:8090/api/data';

  constructor(
    private http: HttpClient
  ) { }

  public getString(): Observable<Item[]> {
    return this.http.get<Item[]>(this.url);
  }
}
app.module.ts
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<button mat-raised-button color="primary" (click)="onClick()">ボタン</button>
<div>
    {{this.title}}
</div>

・app.component
appServiceを呼び出し、取得した値をthis.titleに設定

・app.service
  Angularでは特定の実装やインターフェースの名称ではなく、
  単一の機能のための作られたものまとめてサービスと呼ぶ。
  @Injectable()を付与することでクラスをサービスとしてコンポーネントに引き渡せるようになる。
  HttpClientはHTTP要求を送信し、URIで識別されるリソースからHTTP応答を受信する。

・app.module
  HttpClientModule、HttpClientJsonpModule を追加

・app.component.html
  {{this.title}}でAppComponentで設定した値を表示させる

動作確認

ボタン押下前
7.png
ボタン押下後
8.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1