【问题标题】:Angular HttpClient POST request not interacting with Spring ControllerAngular HttpClient POST 请求不与 Spring Controller 交互
【发布时间】:2021-10-13 10:55:41
【问题描述】:

我在从 Angular 前端服务类向我的 Spring 后端控制器发出 POST 请求时遇到问题。

我正在尝试从控制器获取要显示的 log.info 消息,但除非我手动使用 Swagger 进行调用,否则它不起作用。

我认为问题不在于 Java Rest Controller,因为 Swagger 可以调用它。

我不认为我的服务类发布请求没有被调用存在问题,因为我能够显示 console.log 消息。

我认为我的服务类中的 resourceUrl 没有问题,因为它可以与其他 REST 调用一起正常工作。

我认为这与我格式化 postRequest 的方式有关。

(Typescript 服务类)

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SERVER_API_URL } from 'app/app.constants';
import { DataModel} from 'app/shared/model/data-model.model';

@Injectable({ providedIn: 'root' })
export class DataModelService {
  public resourceUrl = SERVER_API_URL + 'services/api/data-model';

  constructor(protected http: HttpClient) {}

  postRequest(dataModel: DataModel, status: string): Observable<DataModel> {
    console.log('post rest service called with status ' + status);
    return this.http.post<DataModel>(`${this.resourceUrl}/${status}`, dataModel);
  }

(Typescript 组件类)

export class Component implements OnInit, OnDestroy {
...

  constructor( protected dataModelService DataModelService) { }

  userClicks(dataModel: DataModel): void {
    /* eslint-disable no-console */
    console.log('button clicked');
    console.log(dataModel);
    /* eslint-enable no-console */

    this.dataModelService.postRequest(dataModel, 'Status changed');
  }

(Java Spring REST 控制器)

@RestController
@RequestMapping("/api")
public class RestResource {

    @PostMapping("/data-model/{status}")
    public ResponseEntity<DataModelDTO> create(@Valid @RequestBody DataModelDTO dataModelDTO, @PathVariable String status) throws URISyntaxException{
        log.info(dataModelDTO.toString() + " status " + status);
        return ResponseEntity.ok().body(dataModelDTO);    
    }
}

【问题讨论】:

  • 你打开浏览器的开发工具了吗?有什么错误吗?发送的http请求看起来不错吗?您是否订阅了您的 POST 的 Observable
  • OK 我正在查看“网络”选项卡中的开发工具,但没有看到 REST 调用被触发(没有错误)。我没有订阅,让我添加我的 Typescript 组件类来帮助..
  • 请在您使用 POST 请求的位置添加代码。
  • 我添加了我的组件类。
  • Angular 正在搜索 SERVER_API_URL + 'services/api/data-model' 下的服务;在春天,它似乎缺少“服务”

标签: angular spring rest angular-httpclient


【解决方案1】:

你需要subscribeObservable,否则请求不会被触发。 Observables 是“惰性的”。

this.dataModelService.postRequest(dataModel, 'Status changed')
  .subscribe(response => {
    // Do something with the response optionally
  }, error => {
    // Do something if an error occurs
  });

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 2015-11-07
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多