Refre sh angular таблица материалов без перезагрузки после сырой операции - PullRequest
0 голосов
/ 12 марта 2020

привет, я использую angular (v.9) и использую asp. net core web api и ef core (v 3.1) для выполнения операций crud

У меня есть форма компонента региона, которую я использовал здесь в качестве диалога region form

html код для формы regiondetails. html

<form [formGroup]="service.form"  (submit)="onsubmit()" min-width="200px">

    <mat-toolbar color="primary" width="auto">
            <span>Region</span>

    <span class="fill-remainings"></span>   
    <span>  <button mat-button matSuffix mat-icon-button arial-label="Clear" tabindex="1" (click)="onclose()"><mat-icon>close</mat-icon></button></span>      
    </mat-toolbar><br>
    <mat-grid-list cols="1" rowHeight="300px" min-width="100px">
        <mat-grid-tile>
            <div class="controles-container">
                <input formControlName="Id" type="hidden">
                <mat-form-field>
                    <input maxlength="6" formControlName="Code"  (keyup)= "service.checkcode()"matInput placeholder="Code*"  tabindex="2" autocomplete="off">
                    <mat-error *ngIf="service.form.controls['Code'].errors?.required">the field should not be empty</mat-error>
                    <mat-error *ngIf="service.form.controls['Code'].errors?.pattern">Enter only Alphabetic characters</mat-error>
                    <mat-error *ngIf="service.form.controls['Code'].errors?.notUnique">Code already exist</mat-error>
                </mat-form-field><br><br>
                <mat-form-field>
                    <input maxlength="50" formControlName="Description" matInput placeholder="Description*" tabindex="3" autocomplete="off" >
                    <mat-error *ngIf="service.form.controls['Description'].errors?.required">the field should not be empty</mat-error>
                    <mat-error *ngIf="service.form.controls['Description'].errors?.pattern">Enter only  Alphabetic characters</mat-error>
                </mat-form-field>

                <h2 class="example-margin">Active</h2>

                    <mat-slide-toggle
                          class="example-margin" [checked]=lstatus color="primary"  tabindex="4" (change)="toggle($event)"
                          formControlName="Active">
                          <label class="labeltoggle">{{Active}}</label>
                    </mat-slide-toggle>

                    <div class="button-row">

             <button mat-raised-button class="btn warning btn-xs" type="submit" tabindex="5"  [disabled]="service.form.invalid" >Save</button>
             |<button mat-raised-button class="btn btn-primary btn-xs"
                 (click)="onclear()" tabIndex="6" [disabled]= "clear">Clear</button>
            </div>
             </div>
            </mat-grid-tile>
    </mat-grid-list>


</form>

ts файл RegionDetails.ts

onsubmit() {
     debugger
     if (this.service.form.valid) {
       if (this.service.form.get('Id').value) {
          this.service.updateregion(this.service.form.value).subscribe(
           res =>{ this.service.form.reset();
          this.dialogref.close();
        this.notificationService.update('updated Successfully');
           },
           err => {
             console.log(err);
           }
          );

       } else {
         this.service.insertregion(this.service.form.value).subscribe(
           res =>{
             this.service.form.reset();
         this.dialogref.close();
         this.service.initializeForm();
       this.notificationService.success('submitted Successfully');
           },
           err => {
             console.log(err);
           }
         );

       }
     }
   }

insertregion функция в обслуживании

insertregion(region: Region) {
    console.log(region);
   return this.http.post(this.apiurl,region);
  }

моя таблица материалов выглядит следующим образом ... enter image description here

создать функцию кнопки на столе

oncreate() {
   this.service.form.reset();
   this.service.initializeForm();
  const dialogconfig = new MatDialogConfig();
  dialogconfig.disableClose = false;
  dialogconfig.autoFocus = true;
  dialogconfig.width = '400px';
  this.dialog.open(RegionDetailsComponent, dialogconfig);
    this.router.navigateByUrl("Region")
}

я использовал кнопку, чтобы обновить sh страница, на которой функция нажатия кнопки

buttonClick() {
  this.router.navigateByUrl('Country');
  this.router.onSameUrlNavigation;
  this.router.navigateByUrl('Region')
}

, когда я выполняю операцию вставки, таблица не получает refre sh автоматически, но обновляется в базе данных, только получает refre sh после того, как я перехожу на другие URL или перезагружаю страницу ....

любой даст мне решение обновить sh таблицу и страницу без перезагрузки и вставить данные в материале т в состоянии ..... спасибо заранее

1 Ответ

0 голосов
/ 12 марта 2020

Вы можете использовать afterClosed () метод из Angular Диалог. Поэтому вы снова вызываете свой API, когда модальное закрытие.

Когда вы закрываете модальное, вы должны отправить новые значения Region

oncreate() {
  this.dialog
    .open(RegionDetailsComponent, dialogconfig)
    .afterClosed()
      .pipe(
        filter(newValues => !!newValues) // If you have formValues
      ).subscribe(newValues => {
      // YOU HAVE TO REPLACE YOUR TABLE CONTENT WITH newValues
    });
}

И в ваш modal.ts

onsubmit() {
  this.service.updateregion(this.form.value)
    .subscribe(values => this.dialogref.close(values))
}

Обратите внимание, что вы можете go дальше. Я не проверял этот код.

...