【问题标题】:Why doesn't it add proprieties inside of object?为什么不在对象内部添加属性?
【发布时间】:2020-06-11 07:05:16
【问题描述】:

我需要在“sm”对象内的“voci_agg”对象内动态插入属性: sm = { voci_agg: {} };

问题是当我尝试添加时,它会返回: 错误:未捕获(承诺中):TypeError:无法设置未定义的属性'm_motore-radiatore' TypeError:无法设置未定义的属性“m_motore-radiatore”

(m_motore-radiatore 从 DB 中检索并动态添加到“sm.voci_agg”)。

这是感兴趣的代码:

schemamasse-comp.component.html

<tr *ngFor="let voce of voci; let i = index">
 <td class="align-middle">{{ voce.descrizione }}</td>
 <td>
  <input [(ngModel)]="sm.voci_agg[voce.m_model]" class="form-control" (keyup)="cal_m_utile($event)" type="number" step="any" min="0" name="{{ voce.m_model }}" id="{{ i }}"/>
 </td>
 <td>
  <input [(ngModel)]="sm.voci_agg[voce.d_model]" class="form-control" type="number" step="any" min="0" name="{{ voce.d_model }}" id="{{ i }}"/>
 </td>
 <td><a class="btn btn-danger btn-sm" (click)="del_voce($event)" id="{{ i }}"><i class="fas fa-minus"></i></a></td>
</tr>

schemamasse-comp.component.ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { LocalStorageService } from 'ngx-webstorage';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { VociAggiuntive } from './vociaggiuntive.model';

// Modal "VOCI AGGIUNTIVE"
@Component({
  template: `
    <div class="modal-header">
      <h4 class="modal-title">Voci aggiuntive</h4>
      <button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')"><span aria-hidden="true">&times;</span></button>
    </div>
    <div class="modal-body">
      <div class="row form-group text-center p-1 bg-dark text-white">
        <div class="col"><label for="descrizione"><h6>Descrizione</h6></label></div>
        <div class="col"><button class="btn btn-outline-success" (click)="submit_add_voce()">Aggiungi</button></div>
        <div class="col"><button class="btn btn-outline-primary" (click)="get_voci_aggiuntive()">Aggiorna</button></div>
        <div class="col"><button class="btn btn-outline-danger" (click)="submit_delete_voce()">Elimina</button></div>
      </div>
      <div *ngFor="let voce of voci_aggiuntive" class="row form-group text-center p-1">
        <div class="col btn-group btn-group-toggle"><label ngbButtonLabel class="btn-primary"><input ngbButton (change)="check_voce($event)" type="checkbox" value="{{ voce._id }}"/>{{ voce.descrizione }}</label></div>
        <div *ngIf="selected[voce._id] === true" class="col"><i class="fas fa-check fa-2x text-success"></i></div>
      </div>
    </div>
    <div class="modal-footer"><button class="btn btn-outline-primary" (click)="open()">Crea nuova voce</button></div>
    <div *ngIf="response === true" class="alert alert-success alert-dismissible fade show">
          <button type="button" class="close" data-dismiss="alert">&times;</button><strong>{{ message }}</strong>
    </div>
    <div *ngIf="response === false" class="alert alert-danger alert-dismissible fade show">
      <button type="button" class="close" data-dismiss="alert">&times;</button><strong>{{ message }}</strong>
    </div>
    `
})
export class VociAggiuntiveComponent{
  public voci_aggiuntive: VociAggiuntive[] = [];
  response; message; arr_check = []; selected = {};
  constructor(private http: HttpClient, private modalService: NgbModal, public activeModal: NgbActiveModal){
    this.get_voci_aggiuntive();
  }

  get_voci_aggiuntive(){
    this.http.get<VociAggiuntive[]>(`${origin}/api/get_voci_aggiuntive`).subscribe(res => { this.voci_aggiuntive = res });
  }
  check_voce(event){
    let i;
    if(event.target.checked === true){ this.arr_check.push(event.target.value); this.selected[event.target.value] = true; }
    else if (event.target.checked === false){
      for(i = 0; i < this.arr_check.length; i += 1){
        if(event.target.value === this.arr_check[i]){ this.arr_check.splice(i, 1); this.selected[event.target.value] = false; } 
      }
    }
  }
  open(){
    this.modalService.open(CreaNuovaVoceComponent, { backdrop: true, centered: true, scrollable: true, size: 'lg' });
  }
  submit_add_voce(){
    this.http.post<VociAggiuntive[]>(`${origin}/api/load_voci_aggiuntive`, this.arr_check).subscribe(res => { this.activeModal.close(res); });
  }
  submit_delete_voce(){
    let sinplu = this.arr_check.length;
    if(confirm('Sei sicuro di voler eliminare le voci selezionate? \n\n !!! ATTENZIONE !!! \nL\'operazione non è reversibile!')){
      this.http.post<VociAggiuntive[]>(`${origin}/api/delete_voci_aggiuntive`, this.arr_check)
      .subscribe(res => {
        if(sinplu < 2){ this.message = 'Voce aggiuntiva eliminata'; }
        else{ this.message = 'Voci aggiuntive eliminate'; }
        this.response = true;
        this.get_voci_aggiuntive();
        setTimeout (() => {
          this.response = undefined;
        }, 2000);
      }, err => {
        console.log(err);
        this.response = false;
        this.message = 'Errore Server Interno';
      });
    }
  }
}

// Main component
@Component({
  selector: 'app-schema-masse',
  templateUrl: './schemamasse-comp.component.html'
})
export class SchemaMasseComponent{
  sm = { voci_agg: {} };
  voci_aggiuntive(){
    const modalRef = this.modalService.open(VociAggiuntiveComponent, { centered: true, scrollable: true, size: 'lg' });
    modalRef.result.then((res) =>{
      if(res){
        for(let index in res){
          this.sm.voci_agg[res[index].m_model] = 0;
          this.sm.voci_agg[res[index].d_model] = 0;
          this.voci.push(res[index]);
          console.log(this.sm);
        }
      }
    });
  }
  del_voce(event){
    this.voci.splice(event.target.id, 1);
  }
}

【问题讨论】:

  • 你是否像m_motore-radiatore = {}一样初始化m_motore-radiatore
  • 不,因为 m_motore-radiatore 必须添加到 sm.voci_agg 中,所以我可以称之为:sm.voci_agg['m_motore-radiatore']。结构为:sm{ key1: 123, key2: 123, voci_agg{ m_motore-radiatore: 123 }}
  • 我无法完全理解代码,你能告诉我抛出该错误的代码行在哪里吗?
  • 你正在初始化 sm = { voci_agg: {} };然后 this.sm.voci_agg[res[index].m_model].
  • (Aggiungo un consiglio: abituati a crivere codice in inglese)

标签: javascript angular forms object dynamic


【解决方案1】:

已解决,我必须声明一个临时对象,插入我需要使用的所有属性并将临时对象分配给主对象:

voci_aggiuntive(){
 const modalRef = this.modalService.open(VociAggiuntiveComponent, { centered: true, scrollable: true, size: 'lg' });
    modalRef.result.then((res) =>{
      if(res){
        for(let index in res){
          for(let key in res[index]){ if(key === 'm_model' || key === 'd_model'){ this.tmp_obj_voci[res[index][key]] = 0; }}
          this.sm.voci_agg = this.tmp_obj_voci;
          this.voci.push(res[index]);
        }
      }
    });
  }

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 2021-05-26
    • 2020-03-31
    • 1970-01-01
    • 2018-04-23
    • 2019-11-24
    • 1970-01-01
    • 2017-09-20
    相关资源
    最近更新 更多