【问题标题】:cannot implement post method in angular from spring microservice无法从 spring 微服务中以角度实现 post 方法
【发布时间】:2022-01-08 22:23:39
【问题描述】:

如果您需要任何其他文件或任何其他详细信息,请询问

我的组件名称是 create-booking.component

创建-booking.component.ts 文件

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgForm } from '@angular/forms';

import { Product } from '../service/http-client.service';
import { HttpClientService } from '../service/http-client.service';

@Component({
  selector: 'app-create-booking',
  templateUrl: './create-booking.component.html',
  styleUrls: ['./create-booking.component.css']
})
export class CreateBookingComponent implements OnInit {

  createBooking: Product =new Product("","","","","");//here if I write new Product() it gives //error

  constructor(private httpClientService: HttpClientService, private router:Router, private route:ActivatedRoute){
   
    }

  ngOnInit(): void{//empty method
  
  }


  onSubmit(){
    this.httpClientService.save(this.createBooking).subscribe(result=> 
            this.gotoBookingList());
    this.router.navigate(['http://localhost:9003/api/fetchFlights']);
  }//my method to create booking list
  //Post method under Construction

  gotoBookingList(){
    this.router.navigate(['http://localhost:9003/api/fetchFlights']);
  }//getting routed back to booking List
  
 

创建-booking.html 文件

//我从一个微服务获取到另一个微服务的属性(从 SearchandBooking 到 BookingandPayment)是

//private String bookingId;

//private String bookingDate;

//private String totalPassengers;

//private String flightName;

//private String price;


<form (ngSubmit)="onSubmit()" #nameForm="ngForm" >
    <div class="form-group">
      <label for="bookingId">Id</label>
      <input type="text" class="form-control" id="bookingId"
      required
      [(ngModel)]="createBooking.bookingId" name="bookingId">//accessing bookingId from createbooking
    </div>
  
    <div class="form-group">
      <label for="bookingDate">Date</label>
      <input type="text" class="form-control" id="bookingDate"//accessing booking data form createbooking
      [(ngModel)]="createBooking.bookingDate" name="bookingDate">//accessing booking data form createbooking
    </div>

    <div class="form-group">
        <label for="price">Price</label>
        <input type="text" class="form-control" id="price"
        required
        [(ngModel)]="createBooking.price" name="price">
      </div>

      <div class="form-group">
        <label for="flightName">flightName</label>
        <input type="text" class="form-control" id="flightName"
        required
        [(ngModel)]="createBooking.flightName" name="flightName">
      </div>

    <button type="submit" class="btn btn-default" data-dismiss="modal" >Submit</button>
  </form>

http-client.service.ts 文件//服务文件

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable, retry } from 'rxjs';
import { Router } from '@angular/router';


export class Product {//attributes
  constructor(
    public  bookingId: string,
    public  bookingDate: string,
    public  totalPassengers: string,
    public  flightName: string,
    public  price: string
  ) {
  }
}


@Injectable({
  providedIn: 'root'// This is a service class
})

export class HttpClientService{

  constructor(
    private httpClient: HttpClient//http
  ) { }


  //Post method under Construction
  getProducts(){
      console.log('Test Call');
      return this.httpClient.get<Product[]>('http://localhost:9003/api/fetchFlights');
  }//this method is working fine no issues
  public save(createBooking:any){//saving data method
    return this.httpClient.post('http://localhost:9005/api/postDataOnBooking',createBooking);
  }//this is the method I am trying to send data


  
   
}

// 我能够进行微服务间通信以及获取角度值,但无法发布数据。 //数据没有通过角度发布到后端,我的方法有问题。我想。

product.component.ts 文件

import { Component, OnInit } from '@angular/core';
import {HttpClientService, Product} from '../service/http-client.service';

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

  products: Product[] | undefined;

  constructor(
    private httpClientService: HttpClientService
  ) {
  }

  ngOnInit(): void {
    this.httpClientService.getProducts().subscribe(
      response => this.handleSuccessfulResponse(response),
    );
  }

  handleSuccessfulResponse(response:any) {
      this.products = response;
  }
}

//这是你要的文件

【问题讨论】:

    标签: angular spring microservices


    【解决方案1】:

    尝试给出你传递给后端的数据类型。

    this.httpClient.post<any>('http://localhost:9005/api/postDataOnBooking',createBooking);
    

    如果这不起作用,请查看 Angular 文档: https://angular.io/guide/http#making-a-post-request

    更新

    我会尽量给出更明确的答案:

    由于您想使用 Post 请求传递 Object Product,我建议您将其作为 json 传递,因为这是最常见的方式。

    首先尝试像这样设置Product

    export class CreateBookingComponent implements OnInit {
    
      createBooking = {...new Product, bookingId: "", bookingDate: "", totalPassengers: "", flightName: "", price: ""};
    
    ....
    

    save() 函数中尝试声明您收到的参数应该具有什么类型。在你的情况下是Product

    可以通过多种方式配置请求。这是最适合我的方式:

      public save(createBooking: Product){
        this.httpClient.post<Product>('http://localhost:9005/api/postDataOnBooking',createBooking, {observe: 'response'}).subscribe(result => {
          console.log("The request was a success!")
          },
          () => {console.log("There was an Error")});
      }
    
    

    我更喜欢这种方式,因为我可以订阅请求并且可以处理错误。

    【讨论】:

    • 哪里出错了???
    • @SatyamSingh 如果您的意思是Prodcut 错误,我将不得不查看product.model.ts。检查您是否在构造函数中设置正确。
    • 我添加了文件 product.component.ts 文件
    • 找不到答案
    • 有错误信息吗?请添加。
    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2017-02-12
    • 2023-03-24
    • 2018-03-28
    • 2015-12-10
    相关资源
    最近更新 更多