首页 > 解决方案 > 我在 Angular 中使用 API 的 CRUD 应用程序在更新时不能作为单页应用程序(SPA)工作

问题描述

我已经使用 API 在 Angular 中执行了 CRUD 应用程序,它工作正常,但问题是当我更新值时它没有立即显示更新后的值,我必须重新加载页面。

这是我的app.component.ts

import {Component} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Employee} from './employees';
import {EditComponent} from './edit/edit.component';
import {AppService} from './app.service';
import {Router} from '@angular/router'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [AppService]
})

export class AppComponent {
    form:any = {}
    msg: string = null;
    employees: Employee[];
    constructor(
    public http: HttpClient,private appService:AppService,private router: Router
    ){}

    onSubmit(){ 
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      };

  this.http.post('http://127.0.0.1:8000/api/employee',this.form,httpOptions)
      .subscribe(employee=>{
        employee = employee;
        this.msg = 'Updated successfully!';
        this.getEmployee();
      });
    }

    ngOnInit() {
      this.getEmployee();
    }

    getEmployee():void{
       this.appService.getEmployees().subscribe(employees=>(this.employees = employees))
    }

    delete(employee: Employee): void{

      if(confirm("Are you sure want to delete ?")) {
        console.log("user details delete successfully!!");
      this.employees = this.employees.filter(h =>h !== employee);
      this.appService.deleteEmployees(employee.id).subscribe();
      this.msg = 'Employee  details delete successfully!!';
      }else{

    }
  }

      public editComponent: boolean = false;
      loadMyChildComponent($id) 
      {
        this.editComponent = true;
        this.appService.setCurrentId($id);
      }

}   

这是我的edit.component.ts:

import {Component, OnInit, Input} from '@angular/core';
import {AppService} from '../app.service';
import {Employee} from '../employees';
import {Router} from '@angular/router'; 
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {NgForm} from '@angular/forms';
import {Observable} from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})

export class EditComponent implements OnInit {
  @Input() employee: Employee[];
  form:any = {}
  msg: string = null;

  constructor(public http: HttpClient,private appService:AppService,private router: Router,private route: ActivatedRoute) { }

  ngOnInit(){
    this.editEmployees();
  }

  editEmployees():void{
    const id =  this.appService.getCurrentId();
    this.appService.editEmployees(id).subscribe(employee => {
    this.employee = employee;
    this.editEmployees();
   });
  }

  onformSubmit() 
  { 
     this.appService.updateEmployees(this.employee).subscribe(employee=>{
     this.employee = employee;
     this.msg = 'Updated successfully!';
    });

  }
}

这是我的employees.ts

export interface Employee{
    id: number;
    username:string;
    email:string;
    mobile:string;
    password:string;
}

这是我的app.component.html:我在其中显示值和编辑按钮。

<table class="table"> 
  <tr>
  <th>Id</th>
  <th>User Name</th>
  <th>Email</th>
  <th>Mobile</th>
  <th>Edit</th>
  <th>Delete</th>
  </tr>
  <tr *ngFor="let employee of employees">
    <td>{{employee.id}}</td>
    <td>{{employee.username}}</td>
    <td>{{employee.email}}</td>
    <td>{{employee.mobile}}</td>
    <td><button (click)="loadMyChildComponent(employee.id);" class="btn btn-primary" [routerLink]="['/edit',employee.id]">Edit</button></td>
    <td><button class="btn btn-danger" (click)="delete(employee)" > Delete</button></td>
</table>

在此处输入图像描述

这是我的edit.component.html

<div class="mydiv22">
    <p class="msg_success">{{ msg }}</p>
    <h2>Update Form</h2>
      <div class="row">
        <div class="col-md-12">
            <form name="form"  (ngSubmit)="f.form.valid && onformSubmit()" #f="ngForm" novalidate>

            <div class="form-group">
              <label for="username">User Name</label>
              <input type="text" class="form-control" name="username" [(ngModel)]="this.employee.username" #username="ngModel"
                [ngClass]="{'is-invalid': f.submitted && username.invalid}" required id="username"/>
              <div *ngIf="f.submitted && username.invalid" class="invalid-feedback">
                <div *ngIf="username.errors.required">>> required</div>
              </div>
            </div>
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="email" [(ngModel)]="this.employee.email" #email="ngModel" [ngClass]="{'is-invalid': f.submitted && email.invalid}"
                required email placeholder="Enter your email address" id="email"/>
              <div *ngIf="f.submitted && email.invalid" class="invalid-feedback">
                <div *ngIf="email.errors.required">>> required</div>
                <div *ngIf="email.errors.email">>> must be a valid email address</div>
              </div>
            </div>
            <div class="form-group">
                <label for="mobile">Mobile</label>
                <input type="number" class="form-control" name="mobile" [(ngModel)]="this.employee.mobile" #mobile="ngModel"
                  [ngClass]="{'is-invalid': f.submitted && mobile.invalid}" required placeholder="Enter your mobile" pattern="[789][0-9]{9}" minlength="10" id="mobile"/>
                <div *ngIf="f.submitted && mobile.invalid" class="invalid-feedback">
                  <div *ngIf="mobile.errors.required">>> required</div>
                  <div *ngIf="mobile.errors.pattern">>>Please enter a valid mobile number</div>
                </div>
              </div>
            <div class="form-group">
              <label for="password">Password</label>
              <input type="password" class="form-control" name="password" [(ngModel)]="this.employee.password" #password="ngModel"
                [ngClass]="{'is-invalid':f.submitted && password.invalid}" required minlength="6" placeholder="Create your password" id="password"/>
              <div *ngIf="f.submitted && password.invalid" class="invalid-feedback">
                <div *ngIf="password.errors.required">>> required</div>
                <div *ngIf="password.errors.minlength">>> must be at least 6 characters</div>
              </div>
            </div>
            <div class="form-group">
              <button routerLink="/edit" class="btn btn-success">Update</button>

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

流程是:当我单击 app.component.html 中的编辑按钮时,它将获取 id 并转到 app.component.ts。从 app.component.ts 到 app.service.ts,它将使用特定的 Id 从 API 获取值。从 app.service.ts,它会将值传递给 edit.component.ts 并使用 edit.component.ts,它将值传递给 edit.component.html。

它执行每件事都很好,就像添加它立即显示的值一样,我不必重新加载页面,但是在更新我们必须重新加载页面的值时,它不像 SPA 那样立即显示。

我想立即显示更新的值而不更新页面。任何帮助深表感谢。

标签: htmlangularlaraveltypescript

解决方案


您在同一页面中有三个组件,这是关于组件交互的。

在 to 中添加Outputevent 属性,EditComponent在编辑 employee 后发出事件,如下所示:

import { Output, EventEmitter } from '@angular/core'

export class EditComponent {

  @Output() updated = new EventEmitter<Employee>();

  onFormSubmit() { 
    this.appService.updateEmployees(this.employee).subscribe(employee=>{
      this.employee = employee;
      this.msg = 'Updated successfully!';
      // fire an updated event after edit employee.
      this.updated.emit(employee)
    });
  }

}

然后,订阅 中的事件app.component.html,如下所示:

<app-edit (updated)="onUpdated()"></app-edit>

然后,调用方法getEmployeeonUpdated重新加载员工列表,如下所示:

export class AppComponent {

  onUpdated() {
    this.getEmployee();
  }

}

更多内容请参考https://angular.io/guide/component-interaction

您可以将类似的逻辑添加到 RegisterComponent 以重新加载。


推荐阅读