【问题标题】:Updating Angular DOM immediately after editing data and retrieving from the database在编辑数据并从数据库中检索后立即更新 Angular DOM
【发布时间】:2019-11-15 18:55:01
【问题描述】:

我正在开发一个使用 Angular 8 前端和 Laravel 后端构建的单页应用程序。它是一个 CRUD 应用程序,在删除功能上,它通过删除数据库上特定 id 的用户运行良好。删除特定 id 的用户后,我正在从数据库中获取所有产品,但我想用新数据(不包括已删除的资源)重新更新 U.I 上的数据。

请帮忙?

Show.component.ts 文件

import { Component, OnInit , ViewChild, ElementRef} from '@angular/core';
import { SharedService } from 'src/app/Services/shared.service';
import { AuthService } from 'src/app/Services/auth.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import {  SnotifyService } from 'ng-snotify';

@Component({
  selector: 'app-show',
  templateUrl: './show.component.html',
  styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {
  public userData : any[];
  public error = null;

  constructor(
    private Shared : SharedService,
    private Auth:AuthService,
    private router: Router,
    private Notify:SnotifyService
    ) { }

  //Update the data when the DOM loads
  ngOnInit() {
    this.Shared.checkAll$.subscribe(message => this.userData = message);
  }

  //Method called when the delete button is triggered from the html
  //Inside it we submit the data to the backend via a service and get
  //the response
  deleteUser(id:number){
    return this.Auth.delete(id).subscribe(
      data => this.handleDeleteResponse(data),
      error => this.handleDeleteError(error)
    );
  }

  //data below contains data from the backend after successful deletion
  handleDeleteResponse(data:any){
    this.Notify.success(`Successfully Deleted in our records`, {timeout:4000});
  }

  handleDeleteError(error:any){
    console.log(error);
  }

}

【问题讨论】:

  • 您可以从数据库中重新获取新数据并再次将其分配给 userData,就像您在 ngOnInit() 中所做的那样
  • 删除成功后,需要更新与ui绑定的变量。如果可变数据发生变化,UI 将反映新的变化。

标签: javascript angular dom crud


【解决方案1】:

在你的handleDeleteResponse方法中,如果数据是userDatathis.userData = data,或者在你的delete方法订阅中的Js中简单地从数组中删除用户id。

喜欢:

this.userData = this.userData.filter(user => user.id !== idToDelete )

【讨论】:

    【解决方案2】:

    方法一: 在您的服务中定义一个主题并在服务中订阅该主题以接收数据。在组件中,将生命周期挂钩更改为“onChanges”。一旦接收/更新主题中的数据(使用已删除的记录),ngChanges 就会将其反映在 DOM 中。

    方法二: 以列表的形式跟踪前端的记录,当服务给出删除响应为成功时,然后使用 ID 或任何其他唯一标识符删除列表中的该记录。在这种情况下,您无需再次填充所有记录。

    export class MyComponent implements OnInit, OnChanges {
        ngOnChanges() {
        // code here
        }
        ngOnInit() {
         // code here
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-13
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多