简体   繁体   中英

GET request from Angular client to Spring

I have 2 textboxes on my page and one button for summing. I send my numbers to the server and get 404 and HttpErrorResponse. My server accepts these values but doesn't send back a response. I would like to get my value from the server.

My method in the controller.

@CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/greeting")
    public String greeting(@RequestParam String num1, @RequestParam String num2) {
        int sum = 0;
        System.out.println("num1 = "+num1);
        System.out.println("num2 = "+num2);

        try{
            int n1 = Integer.parseInt(num1);
            int n2 = Integer.parseInt(num2);

            sum = n1+n2;
            System.out.println("sum ="+sum);
        }
        catch (Exception|Error e){
            e.printStackTrace();
        }

        return Integer.toString(sum);
    }

Angular's components:

import { Component, OnInit } from '@angular/core';
import { CalculateService } from './calculate.service';


@Component({
  selector: 'app-testsum',
  templateUrl: './testsum.component.html',
  styleUrls: ['./testsum.component.css'],
  providers: [ CalculateService]
})
export class TestsumComponent implements OnInit {

   sum:number;
   num1:number;
   num2:number;
   done:boolean=false;

  constructor(private calculateService: CalculateService) { }

  submit(){
        let rez = this.calculateService.getSum(this.num1, this.num2).subscribe(data => this.sum);
        console.log("rez = "+rez);
        console.log("sum = "+this.sum);
    }

  ngOnInit(): void {
  }

}

Service:

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable()
export class CalculateService{

    constructor(private http: HttpClient){ }

    getSum(num1: number, num2: number){
        return this.http.get('http://localhost:8090/greeting?num1=' + num1 + "&num2=" + num2);
    }
}

You should wrap your Response in a ResponseEntity , it's the entity reponsible for giving a status to your response, for example you respond ok here, so the status will be 200

@CrossOrigin(origins = "http://localhost:4200")
    @GetMapping("/greeting")
    public ResponseEntity<String> greeting(@RequestParam String num1, @RequestParam String num2) {
        int sum = 0;
        System.out.println("num1 = "+num1);
        System.out.println("num2 = "+num2);

        try{
            int n1 = Integer.parseInt(num1);
            int n2 = Integer.parseInt(num2);

            sum = n1+n2;
            System.out.println("sum ="+sum);
        }
        catch (Exception|Error e){
            e.printStackTrace();
        }

        return ResponseEntity.ok().body(Integer.toString(sum));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM