【问题标题】:How to save boolean value with checkbox in MySQL using Angular12?如何使用Angular12在MySQL中使用复选框保存布尔值?
【发布时间】:2021-08-14 23:12:01
【问题描述】:

我正在开发一个连接到 API 和 MySQL 数据库的 Angular 项目。但是我的复选框有问题,当我将订单添加到订单列表时,isDiscount 复选框没有将预期值保存到数据库中。该复选框返回布尔值,但它始终返回 0 值,即使我总是选中 isDiscount 复选框以使值为 True。

这是我在 order.component.html 中的代码

<div class="form group col-md-3">
    <div class="form-check">
      <label class="form-check-inline" for="autoSizingCheck">On Discount Promo?</label><br/>
      <input #isDiscounted
              class="form-check-input"
              type="checkbox"
              id="isDiscounted"
              [checked]="order.isDiscounted == true"
              name="isDiscounted"/>
    </div>
  </div>

这是我的订单。ts

export class Order {
  id: number;
  orderName: string;
  price: number;
  isDiscounted: boolean;
  isDiscountPercentage: number = 5;
}

这是我的 order.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { Order } from './order';
import { map } from 'rxjs/internal/operators/map';

@Injectable({
  providedIn: 'root'
})
export class OrderService {
  order: Order[];
  orders: BehaviorSubject<Order[]> = new BehaviorSubject([]);

  private BASE_URL = environment.apiBaseUrl;
  constructor(
    private http: HttpClient
  ) { }

  public addOrder(order: Order): Observable<Order> {
    return this.http.post<Order>(`${this.BASE_URL}/add`, order)
      .pipe(map((order) => {
        this.order.push(order);
        this.orders.next(this.order);

        return order;
      }));
  }

  public updateOrder(id: number, value: any): Observable<Order> {
    return this.http.put<Order>(`${this.BASE_URL}/update/${id}`, value);
  }

  public deleteOrder(id: number): Observable<any> {
    return this.http.delete(`${this.BASE_URL}/delete/${id}`, {responseType: 'text'});
  }

  public getOrderList(): Observable<Order[]> {
    return this.http.get<Order[]>(`${this.BASE_URL}/orders`)
      .pipe(map((orders) => {
        this.order = orders;
        this.orders.next(this.order);

        return orders;
      }));
  }
}

我的 order.component 打字稿文件没有这样的方法。 我应该添加或修改什么?

【问题讨论】:

  • 您在哪里向您的 API 发送请求? Angular 无法直接与您的数据库交互
  • 我更新了我的问题并添加了我的 order.service.ts ..
  • 不是专家,但是当复选框的值通过分配事件侦听器更改时,您不必告诉它要调用什么吗?

标签: angular typescript checkbox boolean mysql-workbench


【解决方案1】:

试试这个:

<input #isDiscounted
    class="form-check-input"
    type="checkbox"
    id="isDiscounted"
    [checked]="order.isDiscounted"
    (change)="order.isDiscounted = !order.isDiscounted"
    name="isDiscounted"/>

【讨论】:

    猜你喜欢
    • 2015-12-12
    • 2020-03-08
    • 2013-03-20
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多