简体   繁体   English

如何在 Angular 中调用 Java HTTP POST 方法

[英]How to call Java HTTP POST method in Angular

I have the following problem: I created a Java project using Spring boot and MyBatis, I have some classes (for example DirezioneRegionale), with his mapper interface for MyBatis (with the correspondant XML file), his service class and a controller.我有以下问题:我使用 Spring boot 和 MyBatis 创建了一个 Java 项目,我有一些类(例如 DirezioneRegionale),带有 MyBatis 的映射器接口(带有对应的 XML 文件),他的服务类和一个控制器。 I tested the HTTP calls and they works (I'm able to see the result of my queries and they are correct).我测试了 HTTP 调用并且它们有效(我能够看到我的查询结果并且它们是正确的)。

You can see how I implemented the Java and MyBatis part here: Return a List<MyClass> in MyBatis你可以在这里看到我是如何实现 Java 和 MyBatis 部分的: 在 MyBatis 中返回一个 List<MyClass>

Now the problem is that this is part of a greater project, in which i use Angular 8, I should be able to call the HTTP POST method and to have returned, using JSON I suppose, the equivalent of my Java class but in TypeScript.现在的问题是,这是一个更大项目的一部分,我在其中使用了 Angular 8,我应该能够调用 HTTP POST 方法并使用 JSON 返回,我想这相当于我的 Java 类,但在 TypeScript 中。

To do that I have tried the following thing:为此,我尝试了以下操作:

In the app.component.ts I have added:在 app.component.ts 中,我添加了:

allDirReg = this.piuService.getAllDirReg();

In the app.component.html I have added:在 app.component.html 我添加了:

<p>{{ allDirReg }}</p>

So I expected to have returned a list with the id values and description values of my DirezioneRegionale object, but only所以我希望返回一个包含我的 DirezioneRegionale 对象的 id 值和描述值的列表,但只有

[object Object]

appears.出现。

I even tried to change, in the app.component.ts file, the line in this way:我什至尝试在 app.component.ts 文件中以这种方式更改该行:

allDirReg = JSON.stringify(this.piuService.getAllDirReg());

But the result is:但结果是:

{
   "_isScalar": false,
   "source": {
      "_isScalar": false,
      "source": {
         "_isScalar": false,
         "source": {
            "_isScalar": true,
            "value": {
               "url": "localhost:8081/getAllDirRegs",
               "body": null,
               "reportProgress": false,
               "withCredentials": false,
               "responseType": "json",
               "method": "POST",
               "headers": {
                  "normalizedNames": {},
                  "lazyUpdate": null,
                  "headers": {}
               },
               "params": {
                  "updates": null,
                  "cloneFrom": null,
                  "encoder": {},
                  "map": null
               },
               "urlWithParams": "localhost:8081/getAllDirRegs"
            }
         },
         "operator": {
            "concurrent":1
         }
      },
      "operator": {}
   },
   "operator": {}
}

my service's code in Angular is the following:我在 Angular 中的服务代码如下:

  getAllDirReg() {
    const doneCallback = this.loadingService.startLoading();
    return this.http.post<any>(`localhost:8081/getAllDirRegs`, {}).pipe(finalize(doneCallback))
  }

EDIT: This is my Java DirezioneRegionaleController:编辑:这是我的 Java DirezioneRegionaleController:

@RestController
public class DirezioneRegionaleController {

    @Autowired
    private DirezioneRegionaleService direzioneRegionaleService;

    @PostMapping("getAllDirRegs")
    @ResponseBody
    public ResponseEntity<?> getAllDirRegs() {
        List<DirezioneRegionale> allDirRegs = direzioneRegionaleService.getAllDirRegs();
        if (null == allDirRegs) {
            return ResponseEntity.notFound().build();
        }

        List<JSONObject> allDirRegsJSON = new ArrayList<JSONObject>();
        for (DirezioneRegionale dr : allDirRegs) {
            JSONObject drJSON = new JSONObject();
            drJSON.put("id", dr.getID());
            drJSON.put("description", dr.getDescription());
            allDirRegsJSON.add(drJSON);
        }

        return new ResponseEntity<List<JSONObject>>(allDirRegsJSON, HttpStatus.OK);

        // return ResponseEntity.ok(allDirRegs);
    }
}

EDIT 2:编辑2:

What I expect to be returned:我期望返回的内容:

[{"description":"DIR REG CAMPAN BASIL CALABR PUGLIA","direzioniCommerciali":null,"id":"09560"},{"description":"DBT DIREZIONE MILANO E PROVINCIA","direzioniCommerciali":null,"id":"09546"},{"description":"DBT DIR V FVG TR AA","direzioniCommerciali":null,"id":"09547"},{"description":"DBT DIR MILANO E PROVINCIA","direzioniCommerciali":null,"id":"09546"},{"description":"DR EM RO MAR ABR MOL","direzioniCommerciali":null,"id":"09548"},{"description":"DBT DIR V FVG  TR AA","direzioniCommerciali":null,"id":"09547"},{"description":"DBT DIREZIONE PIEMONTE V D'AOSTA LIGURIA","direzioniCommerciali":null,"id":"09544"},{"description":"DR FINAN INST","direzioniCommerciali":null,"id":"11471"},{"description":"DIREZIONE RETE SANPAOLO","direzioniCommerciali":null,"id":"00FIT"},{"description":"DR CAM BA CAL PU SIC","direzioniCommerciali":null,"id":"09560"},{"description":"DIR.GEN.BANCA APULIA","direzioniCommerciali":null,"id":"00FIT"},{"description":"DR TOSC UMB LAZ SARD","direzioniCommerciali":null,"id":"09549"},{"description":"DIREZIONE GENERALE -  BANCO DI NAPOLI","direzioniCommerciali":null,"id":"00FIT"},{"description":"COORDINAMENTO SERVIZIO GESTORE REMOTO","direzioniCommerciali":null,"id":"20233"},{"description":"DBT DIREZIONE LOMBARDIA","direzioniCommerciali":null,"id":"09545"},{"description":"DIREZIONE GENERALE","direzioniCommerciali":null,"id":"00FIT"},{"description":"DBT DIR CAMP BASIL CAL E PUG","direzioniCommerciali":null,"id":"09560"},{"description":"DBT DIR VEN FVG E TR AA","direzioniCommerciali":null,"id":"09547"},{"description":"DBT DIR MI E PROV","direzioniCommerciali":null,"id":"09546"},{"description":"DIR REG TOSCANA E UMBRIA","direzioniCommerciali":null,"id":"09549"},{"description":"DIR REG LAZIO SARDEGNA E SICILIA","direzioniCommerciali":null,"id":"09590"},{"description":"DIREZIONE GENERALE CRFORLI' E ROMAGNA","direzioniCommerciali":null,"id":"00FIT"},{"description":"DR CAM BA CAL PU","direzioniCommerciali":null,"id":"09560"},{"description":"DR GLOBAL CORPORATE","direzioniCommerciali":null,"id":"11474"},{"description":"DR TOS UMB LAZ E SAR","direzioniCommerciali":null,"id":"09549"},{"description":"D.R.CA.BA.CAL.PU.","direzioniCommerciali":null,"id":"09560"},{"description":"DBT DIREZIONE VEN FRIULI VG E TRENTIN AA","direzioniCommerciali":null,"id":"09547"},{"description":"DR TOS E UMB","direzioniCommerciali":null,"id":"09549"},{"description":"DIREZ. S. PAOLO B.CO DI NAPOLI","direzioniCommerciali":null,"id":"00FIT"},{"description":"DR GLOB CORP","direzioniCommerciali":null,"id":"11474"},{"description":"DBT DIR PIEM VAL D'AOS E LIG","direzioniCommerciali":null,"id":"09544"},{"description":"DIR REG EMILIA R,MARCHE,ABRUZZO,MOLISE","direzioniCommerciali":null,"id":"09548"},{"description":"DIREZIONE GENERALE CARISBO","direzioniCommerciali":null,"id":"00FIT"},{"description":"DBT DIR PIEM VDA LIG","direzioniCommerciali":null,"id":"09544"},{"description":"DBT DIR EMIL MAR ABR E MOL","direzioniCommerciali":null,"id":"09548"},{"description":"DIREZIONE GENERALE CR VENETO","direzioniCommerciali":null,"id":"00FIT"},{"description":"DIREZIONE GENERALE CR FVG","direzioniCommerciali":null,"id":"00FIT"},{"description":"DR LAZIO SAR E SIC","direzioniCommerciali":null,"id":"09590"},{"description":"DBT DIR LOMBARDIA","direzioniCommerciali":null,"id":"09545"}]

EDIT 3: My app.component.ts:编辑 3:我的 app.component.ts:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  constructor(
    private piuService: PiuService) {
  }
  title = "PIU Versione 2";

  allDirReg = this.piuService.getAllDirReg().subscribe(bodyRes => { this.allDirReg = JSON.stringify(bodyRes)})

}

The JSON you see there, is the structure of the Observable class你在那里看到的 JSON 是Observable类的结构

HttpClient.post method returns an Observable<T> on which you have to call the subscribe method to be able to treat the server response once you received it. HttpClient.post方法返回一个Observable<T> ,您必须在其上调用subscribe方法才能在收到服务器响应后对其进行处理。 It's an asynchronous mechanism.这是一种异步机制。

example:例子:

...
this.piuService.getAllDirReg().subscribe(bodyRes=> { this.allDirReg = bodyRes });
...

this is to access the response body, but you can access response itself.这是访问响应正文,但您可以访问响应本身。 Take a look at HttpClient methods definitions.查看 HttpClient 方法定义。 You can provide some options to get what you want.你可以提供一些选项来获得你想要的。

EDIT: As you didn't provide options to the post method, I assumed that the default observe option was the HttpResponse.编辑:由于您没有为 post 方法提供选项,我假设默认的observe选项是 HttpResponse。 It seems that its the body itself.似乎是身体本身。 I've edited the example in consquences.我已经在结果中编辑了这个例子。

EDIT2: After seeing your component class, some things are wrong there. EDIT2:在看到你的组件类之后,有些地方是错误的。 Version that should work:应该工作的版本:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  constructor(private piuService: PiuService) {
  }
  title = "PIU Versione 2";
  allDirReg = "";

  ngOnInit() {
    this.piuService.getAllDirReg().subscribe(bodyRes => { this.allDirReg = JSON.stringify(bodyRes)})
  }
}

But in this case you work with a stringified model, which is not the main goal.但在这种情况下,您使用的是字符串化模型,这不是主要目标。 You should use defined class models when working with TS and Angular.在使用 TS 和 Angular 时,您应该使用定义的类模型。 I suggest you to follow an Angular tutorial.我建议您遵循 Angular 教程。 You can try with Tour of Heroes which is the Google's introduction tutorial to Angular.您可以尝试使用 Tour of Heroes,这是 Google 对 Angular 的介绍教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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