Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Angular 8中的嵌套对象数组中存储值_Angular_Angular8_Angular Arrays - Fatal编程技术网

如何在Angular 8中的嵌套对象数组中存储值

如何在Angular 8中的嵌套对象数组中存储值,angular,angular8,angular-arrays,Angular,Angular8,Angular Arrays,我正在创建一个订单输入表单,我们将在其中存储主数据和详细数据。下面,我向您展示我用typescript编写的实体详细信息 export interface IOrder { id: number; customerId: number; orderDate: Date; orderAmount: number; orderDiscount: number; finalAmount:

我正在创建一个订单输入表单,我们将在其中存储主数据和详细数据。下面,我向您展示我用typescript编写的实体详细信息

 export interface IOrder {   
       id: number;   
       customerId: number;  
       orderDate: Date;   
       orderAmount: number;   
       orderDiscount: number; 
       finalAmount: number;   
       status: string;   
       orderDetail: IOrderDetail[];
    }
    export interface IOrderDetail {
        id: number;  
        serviceName: string;
        serviceDescription: string;
        quantity: number;
        price: number;
        discount: number;
        amountAfterDiscount: number;
     }
下面是我的表单截图:

  export class AddorderComponent implements OnInit {
      dbops = DBOperation.create;
      orderForm: FormGroup;
      itemList: IServiceOffer[];
      custList: ICustomer[];
      id: number;
      order: IOrder;
      errorMessage: any;
      title: string;  
      itemCount: number;

   constructor(private _fb: FormBuilder, private calendar: NgbCalendar,
private _avRoute: ActivatedRoute,
private _orderService: OrderService,
private _router: Router) {
if (this._avRoute.snapshot.params["id"]) {
  this.id = this._avRoute.snapshot.params["id"];
}
this.orderForm = this._fb.group({
  id: ['', [Validators.required]],
  customerId: ['', [Validators.required]],      
  orderDate: ['', [Validators.required]],
  orderAmount: [ '' , [Validators.required]],
  orderDiscount: [''],
  finalAmount: [''],
  status: [''],
  serviceId: [''],
  serviceName: ['', [Validators.required]],
  serviceDescription: ['',[Validators.required]],
  price: [''],
  quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
  discount: [ '', [Validators.pattern("^[0-9]*$")]],
  amountAfterDiscount: [''] 
  });
}
 ngOnInit() {
   this.getCustomerList();
   this.getServiceList();
   if (this.id > 0) {
    this.editOrder(this.id);
    // console.log(this.customer);
    } else {
     this.addOrder();
   }
  }

saveOrder() {
 this.order = this.orderForm.value;
  if (!this.orderForm.valid) {
  return;
}
if (this.dbops == DBOperation.create) {
  console.log(this.order);

  this._orderService
    .saveOrder(Global.BASE_API_ENDPOINT + "order/add", this.order)
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  } else if (this.dbops == DBOperation.update) {
    this._orderService
    .updateOrder(
      Global.BASE_API_ENDPOINT + "order/update",
      this.order
    )
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  }
 }
 cancel() {
    this._router.navigate(["order"]);
  }
 addOrder() {
    this.dbops = DBOperation.create;
    this.title = "Add New Order";
  }

editOrder(id: number) {
   this.dbops = DBOperation.update;
   this.title = "Edit Order";
   this._orderService
     .getOrderById(Global.BASE_API_ENDPOINT + "order/details", id)
     .subscribe(data => this.orderForm.setValue(data));
  }
 getCustomerList() {
    this._orderService
    .getCustomerList(Global.BASE_API_ENDPOINT + "customer/allcustomer")
    .subscribe(data => (this.custList = data));
}
 getServiceList() {
    this._orderService
   .getServiceList(Global.BASE_API_ENDPOINT + "serviceoffer/allservice")
   .subscribe(data => (this.itemList = data));
 }

addToGrid() {
   this.itemCount=(this.order.orderDetail.length);  
   this.order.orderDetail[this.itemCount].id = 0;
   this.order.orderDetail[this.itemCount].serviceDescription 
        = this.serviceDescription.value;
   this.order.orderDetail[this.itemCount].serviceName 
        = this.serviceName.value;
   this.order.orderDetail[this.itemCount].price = this.price.value;
   this.order.orderDetail[this.itemCount].quantity = this.quantity.value;
   this.order.orderDetail[this.itemCount].discount = this.discount.value;
   this.order.orderDetail[this.itemCount].amountAfterDiscount 
       = ((this.quantity.value * this.price.value) - this.discount.value);

        console.log(this.order.orderDetail);
   }

   getServicedetails(value: any) {    
      this._orderService
     .getServiceDetails
          (Global.BASE_API_ENDPOINT + "serviceoffer/details", value)
     .subscribe(data => ( 
       this.serviceDescription.setValue(data.serviceDescription),
        this.serviceName.setValue(data.serviceName),
       this.price.setValue(data.servicePrice)
   ));
 }

 get customerId() {
    return this.orderForm.get("customerId");
 }
 get serviceId() {
    return this.orderForm.get("serviceId");
 }
get serviceName() {
   return this.orderForm.get("serviceName");
}
get serviceDescription() {
   return this.orderForm.get("serviceDescription");
}
get price() {
  return this.orderForm.get("price");
}
get quantity() {
   return this.orderForm.get("quantity");
}
get discount() {
   return this.orderForm.get("discount");
}
get orderDate() {
  return this.orderForm.get("orderDate");
}  
get orderAmount() {
  return this.orderForm.get("orderAmount");
}
get orderDiscount() {
   return this.orderForm.get("orderDiscount");
}
get finalAmount() {
   return this.orderForm.get("finalAmount");
}
get orderDetail() {
  return this.orderForm.get("order.orderDetail[]");
}
get status() {
   return this.orderForm.get("status");
 }

单击加号(+)后,将订单项添加到网格中。 下面提到的功能将完成该工作

addToGrid() {
this.itemCount=(this.order.orderDetail.length);  
this.order.orderDetail[this.itemCount].id = 0;
this.order.orderDetail[this.itemCount].serviceDescription = this.serviceDescription.value;
this.order.orderDetail[this.itemCount].serviceName = this.serviceName.value;
this.order.orderDetail[this.itemCount].price = this.price.value;
this.order.orderDetail[this.itemCount].quantity = this.quantity.value;
this.order.orderDetail[this.itemCount].discount = this.discount.value;
this.order.orderDetail[this.itemCount].amountAfterDiscount = ((this.quantity.value * this.price.value) - this.discount.value);
console.log(this.order.orderDetail);
}
我收到orderDetail未定义错误。请帮我把我的问题简短地说出来

下面是我的Component.ts文件:

  export class AddorderComponent implements OnInit {
      dbops = DBOperation.create;
      orderForm: FormGroup;
      itemList: IServiceOffer[];
      custList: ICustomer[];
      id: number;
      order: IOrder;
      errorMessage: any;
      title: string;  
      itemCount: number;

   constructor(private _fb: FormBuilder, private calendar: NgbCalendar,
private _avRoute: ActivatedRoute,
private _orderService: OrderService,
private _router: Router) {
if (this._avRoute.snapshot.params["id"]) {
  this.id = this._avRoute.snapshot.params["id"];
}
this.orderForm = this._fb.group({
  id: ['', [Validators.required]],
  customerId: ['', [Validators.required]],      
  orderDate: ['', [Validators.required]],
  orderAmount: [ '' , [Validators.required]],
  orderDiscount: [''],
  finalAmount: [''],
  status: [''],
  serviceId: [''],
  serviceName: ['', [Validators.required]],
  serviceDescription: ['',[Validators.required]],
  price: [''],
  quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
  discount: [ '', [Validators.pattern("^[0-9]*$")]],
  amountAfterDiscount: [''] 
  });
}
 ngOnInit() {
   this.getCustomerList();
   this.getServiceList();
   if (this.id > 0) {
    this.editOrder(this.id);
    // console.log(this.customer);
    } else {
     this.addOrder();
   }
  }

saveOrder() {
 this.order = this.orderForm.value;
  if (!this.orderForm.valid) {
  return;
}
if (this.dbops == DBOperation.create) {
  console.log(this.order);

  this._orderService
    .saveOrder(Global.BASE_API_ENDPOINT + "order/add", this.order)
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  } else if (this.dbops == DBOperation.update) {
    this._orderService
    .updateOrder(
      Global.BASE_API_ENDPOINT + "order/update",
      this.order
    )
    .subscribe(
      () => {
        this._router.navigate(["order"]);
      },
      error => (this.errorMessage = error)
    );
  }
 }
 cancel() {
    this._router.navigate(["order"]);
  }
 addOrder() {
    this.dbops = DBOperation.create;
    this.title = "Add New Order";
  }

editOrder(id: number) {
   this.dbops = DBOperation.update;
   this.title = "Edit Order";
   this._orderService
     .getOrderById(Global.BASE_API_ENDPOINT + "order/details", id)
     .subscribe(data => this.orderForm.setValue(data));
  }
 getCustomerList() {
    this._orderService
    .getCustomerList(Global.BASE_API_ENDPOINT + "customer/allcustomer")
    .subscribe(data => (this.custList = data));
}
 getServiceList() {
    this._orderService
   .getServiceList(Global.BASE_API_ENDPOINT + "serviceoffer/allservice")
   .subscribe(data => (this.itemList = data));
 }

addToGrid() {
   this.itemCount=(this.order.orderDetail.length);  
   this.order.orderDetail[this.itemCount].id = 0;
   this.order.orderDetail[this.itemCount].serviceDescription 
        = this.serviceDescription.value;
   this.order.orderDetail[this.itemCount].serviceName 
        = this.serviceName.value;
   this.order.orderDetail[this.itemCount].price = this.price.value;
   this.order.orderDetail[this.itemCount].quantity = this.quantity.value;
   this.order.orderDetail[this.itemCount].discount = this.discount.value;
   this.order.orderDetail[this.itemCount].amountAfterDiscount 
       = ((this.quantity.value * this.price.value) - this.discount.value);

        console.log(this.order.orderDetail);
   }

   getServicedetails(value: any) {    
      this._orderService
     .getServiceDetails
          (Global.BASE_API_ENDPOINT + "serviceoffer/details", value)
     .subscribe(data => ( 
       this.serviceDescription.setValue(data.serviceDescription),
        this.serviceName.setValue(data.serviceName),
       this.price.setValue(data.servicePrice)
   ));
 }

 get customerId() {
    return this.orderForm.get("customerId");
 }
 get serviceId() {
    return this.orderForm.get("serviceId");
 }
get serviceName() {
   return this.orderForm.get("serviceName");
}
get serviceDescription() {
   return this.orderForm.get("serviceDescription");
}
get price() {
  return this.orderForm.get("price");
}
get quantity() {
   return this.orderForm.get("quantity");
}
get discount() {
   return this.orderForm.get("discount");
}
get orderDate() {
  return this.orderForm.get("orderDate");
}  
get orderAmount() {
  return this.orderForm.get("orderAmount");
}
get orderDiscount() {
   return this.orderForm.get("orderDiscount");
}
get finalAmount() {
   return this.orderForm.get("finalAmount");
}
get orderDetail() {
  return this.orderForm.get("order.orderDetail[]");
}
get status() {
   return this.orderForm.get("status");
 }

Shiv,问题是您没有初始化orderDetail,但是您还有其他问题,您正在使用一个Estange FormGroup。按步骤:

创建两个返回FormGroup的函数

newOrderForm()
{
   return this._fb.group({
      id: ['', [Validators.required]],
      customerId: ['', [Validators.required]],      
      orderDate: ['', [Validators.required]],
      orderAmount: [ '' , [Validators.required]],
      orderDiscount: [''],
      finalAmount: [''],
      status: [''],
      orderDetail:this.fb.array([])
  })
}

newOrderDetailForm()
{
   return this._fb.group({
      serviceId: [''],
      serviceName: ['', [Validators.required]],
      serviceDescription: ['',[Validators.required]],
      price: [''],
      quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
      discount: [ '', [Validators.pattern("^[0-9]*$")]],
      amountAfterDiscount: [''] 
  });
}
然后使用此函数创建表单,并有一个新的函数getter来管理formArray

 this.orderForm=this.newOrderForm();

 get orderDetail()
 {
      return this.orderForm?this.orderForm.get('orderDetail') as FormArray:null
 }
现在是编写.html的时候了

 <form [formGroup]="orderForm">
     <!---zone of main fields -->
     <input formControlName="customerId">
     <input formControlName="orderDate">
      .....
      <!--zone to manage the formArray--->
      <div formArrayName="orderDetail">
          <div *ngFor="let group of orderDetail.controls;let i=index"
                  [fromGroupName]="i">
               <!---inputs that belong to the array-->
                  <input formControlName="serviceId">
                  <input formControlName="serviceName">

          </div>
      </div>
 </form>

看看这个(这是我最后一次发现的,我认为它非常完整)

Shiv,问题是您没有初始化orderDetail,但您还有其他问题,您正在使用一个Esrange FormGroup。按步骤:

创建两个返回FormGroup的函数

newOrderForm()
{
   return this._fb.group({
      id: ['', [Validators.required]],
      customerId: ['', [Validators.required]],      
      orderDate: ['', [Validators.required]],
      orderAmount: [ '' , [Validators.required]],
      orderDiscount: [''],
      finalAmount: [''],
      status: [''],
      orderDetail:this.fb.array([])
  })
}

newOrderDetailForm()
{
   return this._fb.group({
      serviceId: [''],
      serviceName: ['', [Validators.required]],
      serviceDescription: ['',[Validators.required]],
      price: [''],
      quantity: ['',[Validators.required, Validators.pattern("^[0-9]*$")]],
      discount: [ '', [Validators.pattern("^[0-9]*$")]],
      amountAfterDiscount: [''] 
  });
}
然后使用此函数创建表单,并有一个新的函数getter来管理formArray

 this.orderForm=this.newOrderForm();

 get orderDetail()
 {
      return this.orderForm?this.orderForm.get('orderDetail') as FormArray:null
 }
现在是编写.html的时候了

 <form [formGroup]="orderForm">
     <!---zone of main fields -->
     <input formControlName="customerId">
     <input formControlName="orderDate">
      .....
      <!--zone to manage the formArray--->
      <div formArrayName="orderDetail">
          <div *ngFor="let group of orderDetail.controls;let i=index"
                  [fromGroupName]="i">
               <!---inputs that belong to the array-->
                  <input formControlName="serviceId">
                  <input formControlName="serviceName">

          </div>
      </div>
 </form>

看看这个(这是我最后一次发现它,我认为它非常完整)

您必须分享更多关于表单如何设置的代码(html),但是orderDetail数组似乎还没有初始化。您好,我已经在我的问题中添加了我的component.ts文件的代码。你在哪里设置这个.order.orderDetail的值?@ShivShankarMaiti你需要初始化
this.order={orderDetail:[]}
在addToGrid fn中你必须共享更多关于表单如何设置的代码(html),但是,orderDetail数组似乎还没有初始化。嗨,我已经将我的component.ts文件的代码添加到我的问题中。你在哪里设置这个.order.orderDetail的值?@ShivShankarMaiti你需要在addToGrid中初始化
this.order={orderDetail:[]}
我在这一行中遇到错误:orderDetail:this.fb.formArray([])true,这是.fb.array([]),抱歉(刚刚在答案中更正)我在这行中遇到错误:orderDetail:this.fb.formArray([])true,this.fb.array([]),抱歉(刚刚在答案中更正)