Невозможно добавить или обновить мою объектную модель, используя реактивные формы и webapi - PullRequest
0 голосов
/ 04 мая 2020

когда я отправляю из ничего не происходит !!! я использую реактивные формы для получения данных. Тогда объект модели не обновляется и не отправляется (добавляется) !!!!

это мой код:

HTML file


    <mat-toolbar dir="rtl">
    <span>{{operationService.form.controls['TransID'].value? "تحيين":"عملية جديدة"}}</span>
    <span class="fill-remaining-space"></span>
    <button class="btn-dialog-close" mat-stroked-button (click)="onClose()" tabIndex="-1"><mat-icon>clear</mat-icon></button>
</mat-toolbar>
<form [formGroup]="operationService.form" class="normal-form" dir="rtl" (submit)="onSubmit()" >
<mat-grid-list cols="2" rowHeight="350px">
    <mat-grid-tile>
    <div class="controles-container">
        <input type="hidden" formControlName="TransID">
        <mat-form-field>
            <input formControlName="TransNo" matInput placeholder="عدد الإحالة*">
            <mat-error>تعمير هذه الخانة اجباري</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="Seller" matInput placeholder="xxxx*">
            <mat-error>تعمير هذه الخانة اجباري</mat-error>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="Buyer" matInput placeholder="المشتري*">
            <mat-error>تعمير هذه الخانة اجباري</mat-error>
        </mat-form-field>
        <mat-form-field>
            <mat-select formControlName="Zone" placeholder="xxxx">
                <mat-option>None</mat-option>
                <ng-container *ngFor="let zone of zoneList">
                <mat-option value="{{zone.Zone1}}">{{zone.Zone1}}</mat-option>
                </ng-container>
            </mat-select>
        </mat-form-field>
        <mat-form-field>
            <mat-select formControlName="Statut" placeholder="xxxx">
                <mat-option>None</mat-option>
                <ng-container *ngFor="let state of stateList">
                <mat-option value="{{state.state}}">{{state.state}}</mat-option>
                </ng-container>
            </mat-select>
        </mat-form-field>
    </div>
    </mat-grid-tile>
    <mat-grid-tile>
    <div class="controles-container">
        <mat-form-field>
            <input formControlName="RequestDate" matInput [matDatepicker]="picker" placeholder="تاريخ الإحالة">
            <mat-datepicker-toggle matSuffix [for]="picker" ></mat-datepicker-toggle>
            <mat-datepicker #picker ></mat-datepicker>
        </mat-form-field>
        <mat-form-field>
        <mat-select formControlName="Agent" placeholder="المكلف بدراسة الملف">
                <mat-option>None</mat-option>
                <ng-container *ngFor="let agent of agentList">
                <mat-option value="{{agent.agent}}">{{agent.agent}}</mat-option>
                </ng-container>
        </mat-select>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="LOT" matInput placeholder="المقسم*">
            <mat-error>تعمير هذه الخانة اجباري</mat-error>
        </mat-form-field>
        <mat-form-field>
            <mat-select formControlName="TransType" placeholder="نوع العملية">
                <mat-option>None</mat-option>
                <ng-container *ngFor="let trans of transList">
                <mat-option value="{{trans.type}}">{{trans.type}}</mat-option>
                </ng-container>
            </mat-select>
        </mat-form-field>
        <mat-form-field>
            <input formControlName="Observation" matInput placeholder="ملاحظات عامة">
        </mat-form-field>
        <div class="button-row">
            <button mat-raised-button color="primary" type="submit" [disabled]="operationService.form.invalid">تسجيل</button>
            <button mat-raised-button color="warn" (click)="onClear()">الغاء</button>
        </div>
    </div>
    </mat-grid-tile>
</mat-grid-list>
</form>

компонент файл


onSubmit() {

    if  (this.operationService.form.valid)
    {
     if (!this.operationService.form.get('TransID').value)
        this.operationService.saveOrUpdateOperation(this.operationService.form.value); //add

     else
       this.operationService.saveOrUpdateOperation(this.operationService.form.value);
       this.operationService.form.reset();
       this.operationService.initializeFormGroup();
       this.notificationService.success(':: Submitted successfully');
       this.onClose();
    }
   }

служебный файл

export class OperationService {

  form: FormGroup= new FormGroup({TransID: new FormControl(null),TransNo: new FormControl(null),RequestDate: new FormControl(''),
    Agent: new FormControl(0),TransType: new FormControl(0),Buyer:  new FormControl('', Validators.required),
    LOT:new FormControl(),Seller: new FormControl('', Validators.required),ZoneID: new FormControl(null),
    Zone: new FormControl(0),Statut: new FormControl(0),Observation: new FormControl(''),Gouv:new FormControl('')

  });

  private newOperation: Operations;


  constructor(private http: HttpClient) { 

  }

 initializeFormGroup() {
    this.form.setValue({TransID: null,TransNo:null,RequestDate:'',Agent:0,TransType:0,Buyer: '',
      LOT: '',Seller: '',ZoneID:0,Zone: 0,Statut: 0,Observation:'',Gouv:''

    });
  }

  saveOrUpdateOperation(operation) {

   this.newOperation = new Operations(operation)
   return this.http.post(environment.apiURL + '/Operations', this.newOperation);
  }


это моя модель ==> TransID - это автоматический столбец на sql сервере

Модель

export class Operations {

    TransID: number;TransNo : number;TransType:string;ZoneID: number;
    RequestDate: Date;Agent:string;Buyer:string;Seller:string;LOT:string;
    Gouv:string;Statut:string;Observation:String


    public constructor(init?: Partial<Operations>) {
        Object.assign(this, init);
    }
}
web API
 [ResponseType(typeof(Operation))]
        public IHttpActionResult PostOperation(Operation operation)
        {
            try
            {
                //Operations table
                if (operation.TransID == 0)
                {

                    db.Operations.Add(operation);
                }
                else
                {
                    db.Entry(operation).State = EntityState.Modified;
                }


                db.SaveChanges();

                return Ok();
            }

            catch (Exception ex)
            {

                throw ex;
            }

        }

Метод web api не достигнут, что не так с моим кодом !!!

1 Ответ

0 голосов
/ 04 мая 2020
 <input type="hidden" formControlName="TransID">

TransID никогда не получает значение, поэтому условие при отправке всегда ложное? Я ошибся, оно обновляется в любом случае, поэтому его можно записать короче:

  if  (this.operationService.form.valid && this.operationService.form.get('TransID').value)
      {     
   this.operationService.saveOrUpdateOperation(this.operationService.form.value); <-- this an observable so you need to subscribe it
   this.operationService.form.reset();
   this.operationService.initializeFormGroup();
   this.notificationService.success(':: Submitted successfully');
   this.onClose();
}
...