将请求从服务器发送到Web应用程序

时间:2019-01-16 01:43:46

标签: java angular spring-boot

我不确定我的标题是否能很好地说明我的问题,因此我将尝试在此处进行解释。

我的服务器上有一个springBoot应用程序,并且在前端使用angular。

我向服务器发送请求:

@PostMapping(value="/setup/rate/electricityToImport")
public void updateNewElectricityRate( HttpServletRequest request) throws IOException, SAXException, ParseException {
    String rate = request.getParameter("electricityToImport");      

    system.out.println(rate);

    //here i will save rate in file.

}
var rate = this.myGridImport.getselectedcell()['value'];
console.log(rate)

$.ajax({
  url: "/api/setup/rate/electricityToImport",
  type: 'POST',
  dataType: "text",
  data: 'electricityToImport=' + rate
})

现在,我想知道文件是否已保存,并在正面(角度应用程序)显示“文件已保存” 但是我该如何发送到保存成功的

非常感谢您的帮助! 数学

2 个答案:

答案 0 :(得分:1)

@mavriksc已经显示了正确的方法。通常,您可以通过两种方式实现这一目标:

共享服务

如果您使用共享的全局服务来处理请求,则可以在那里处理响应错误(如果没有错误,则可以告诉客户端成功保存,对吗?)。

可能是这样的:

getJson(): Observable<string> {
    return this.http
      .get(a_url_here)
      .pipe(
      map((res: any) => {
        console.log("Data got: ");
        console.log(res);
        return res;
      }),
      catchError(error => this.handleError<string>(error, "Network Error!"))
    );
  }

独立请求

如果您直接在组件中请求或在那里处理错误,则可以与subscribe()一起实现,如下所示:

this.getYourData(your_url).subscribe(jsonStr => this.testContent = jsonStr, 
                              error => this.handleError<string>(error, "Network Error!"));

答案 1 :(得分:0)

如果从控制器抛出异常,

Web框架将返回错误代码,否则返回200OK。因此,在您的前端前端,您的客户将对此请求有一些可观察的响应。在complete中,您可以显示已保存的文件。在error中,您可以显示有关此信息的信息。