Angular 6 中 MatDialog 关闭且数据库中的数据更新后如何刷新组件?

2023-11-28

我正在学习 Angular 6 的 MEAN 堆栈应用程序。在这里,我想在添加新的客户端/汽车/司机/预订或更新新的客户端/汽车/司机/预订后刷新组件。但是添加新值后,显示所有值的组件不会更新或刷新(当时无法看到当前值),但是当我在组件之间路由然后返回到它更新并显示的同一组件时所有的值。

我希望当从对话框表单添加或更新值时,它会在那时显示出来。

Here is add client component

export class AddClientComponent implements OnInit {

  clientForm: FormGroup;

  constructor(private fb: FormBuilder,
    private clientService: ClientService,
    private toastr: ToastrService,
    private router: Router,
    public dialogRef: MatDialogRef < AddClientComponent > ) {

    this.clientForm = this.fb.group({
      'clientname': new FormControl(""),
      'clientphoneno': new FormControl(""),
      'clientemail': new FormControl(""),
      'clientaddress': new FormControl("")
    });

  }

  ngOnInit() {
    this.router.navigate(['/admin/clients']);
  }

  saveClient(formdata: any) {
    let theForm = this.clientForm.value;
    this.clientService.addClient(theForm).subscribe(data => {
      if (data.success === false) {
        this.toastr.error(data.message);
      } else {
        this.toastr.success(data.message);
        this.ngOnInit();
        this.dialogRef.close();
      }
      this.clientForm.reset();
    });
  }

  close() {
    this.dialogRef.close();
  }

}

这里是client component显示添加值的位置

export class ClientsComponent implements OnInit {

  public currentClient: IClient;
  clients: any;

  addClientDialogRef: MatDialogRef < AddClientComponent > ;
  editClientDialogRef: MatDialogRef < EditClientComponent > ;

  constructor(public dialog: MatDialog,
    private dialogService: DialogService,
    private clientService: ClientService,
    private router: Router) {}

  openAddClientDialog() {
    this.dialogService.open(AddClientComponent, {
      width: '500px'
    })
  }

  openEditClientDialog(id) {
    this.dialogService.open(EditClientComponent, {
      width: '500px',
      data: {
        'id': id
      }
    })
  }

  ngOnInit() {
    this.getAllClients();
  }

  getAllClients() {
    this.clientService.getClients().subscribe((res) => {
      this.clients = res;
    }, err => {
      console.log(err);
    });
  }

  deleteClient(id) {
    this.clientService.deleteClient(id)
      .subscribe(res => {
        this.router.navigate(['./clients']);
        this.ngOnInit();
      }, (err) => {
        console.log(err);
      });
  }


}

这里是client service

addClient(oClient) {
  let headers = new Headers({
    'Content-Type': 'application/json'
  });
  let options = new RequestOptions({
    headers: headers
  });
  return this._http.post('http://localhost:3000/admin/clients/add', JSON.stringify(oClient), options).pipe(
    map((response: Response) => response.json()));
}

getClients() {
  let headers = new Headers({
    'Content-Type': 'application/json'
  });
  let options = new RequestOptions({
    headers: headers
  });
  return this._http.get('http://localhost:3000/admin/clients', options).pipe(
    map((response: Response) => response.json()));
}

getClient(clientid) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  let options = new RequestOptions({
    headers: headers
  });
  return this._http.get(`http://localhost:3000/admin/clients/${clientid}`, options).pipe(
    map((response: Response) => response.json()));
}

editClient(clientId, oClient) {
  let headers = new Headers({
    'Content-Type': 'application/json'
  });
  let options = new RequestOptions({
    headers: headers
  });
  return this._http.put(`http://localhost:3000/admin/clients/edit/${clientId}`, JSON.stringify(oClient), options).pipe(
    map((response: Response) => response.json()));
}

你只是打电话getAllClients()在此期间OnInit的生命周期钩子ClientsComponent。这意味着它将only在组件初始化时加载客户端(这就是为什么当您导航离开并再次返回时,您会看到新客户端,因为组件重新初始化并且OnInit生命周期钩子再次被触发)。

为了解决这个问题,您有两个选择(如果您使用状态管理(例如 ngRx),则有两个以上的选择)。

1)当您添加新客户端并关闭对话框后,立即调用getAllClients()再次,通过订阅afterClosed的事件MatDialog

this.addClientDialogRef.afterClosed().subscribe(() => { this.getAllClients(); } );

or

2) 通过提供新的客户端对象afterClosed来自对话框本身的事件,并将新对象推送给您clients大批。唯一需要注意的是,您需要从 HTTP 请求中返回新的客户端对象saveClient

添加客户端组件

saveClient(formdata: any) {
    let theForm = this.clientForm.value;
    this.clientService.addClient(theForm).subscribe(data => {
       if (data.success === false) {
          this.toastr.error(data.message);
       } else {
          this.toastr.success(data.message);
          this.ngOnInit();
          this.dialogRef.close(data.client); // <--- Assuming the new object comes under the 'client' key of your response.
       }
       this.clientForm.reset();
    });
}

客户端组件

addClientDialogRef.afterClosed().subscribe((client: Client) => {
    this.clients.push(client);
}

The afterClosed事件记录(简要)在这里:https://material.angular.io/components/dialog/overview

MatDialogRef 提供打开的对话框的句柄。有可能 用于关闭对话框并在对话框打开时接收通知 已经被关了。

dialogRef.afterClosed().subscribe(result => {   console.log(`Dialog
   result: ${result}`); // Pizza! });

dialogRef.close('Pizza!');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 6 中 MatDialog 关闭且数据库中的数据更新后如何刷新组件? 的相关文章

随机推荐

  • 我可以在配备英特尔高清显卡的笔记本电脑上实现深度学习模型吗

    我目前正在为我的硕士学位做一个关于深度学习的项目 我想安装 keras 库 所以当我开始安装 Theano 和 tensorflow 时 我发现我必须安装 CUDA 但我的笔记本电脑配备了英特尔高清显卡 所以我的问题是 如果我安装它们 它会
  • Nuxt.js - 在所有网址末尾强制添加斜杠

    我正在寻找一种方法来确保我的所有网址都以尾随斜杠结尾 因此首先检查末尾是否已经有尾随斜杠 如果没有则添加一个 我尝试过nuxt 重定向模块 它可以添加斜杠 但随后会导致无限重定向 redirect from to from req gt l
  • Internet Explorer、Json.Net JavaScript 日期和毫秒问题

    我不确定是否是我遗漏了某些东西 或者 IE 或 Json Net 但基本上这是有效的 new Date 2012 08 03T12 36 54 743Z 此操作失败并出现 无效日期 错误 new Date 2012 08 03T12 36
  • Xcode - 警告:函数的隐式声明在 C99 中无效

    收到警告 函数 Fibonacci 的隐式声明在 C99 中无效 怎么了 include
  • 在 Windows Azure 上运行 Fleck(或任何)Websocket 服务器

    我想在 Azure 中以辅助角色运行 WebSocket 服务器 这在模拟器本地工作得很好 但是第一次运行套接字服务器时会出现 Windows 防火墙提示 我想知道是否有人知道如何克服 Azure 上套接字的连接问题 我的套接字服务器实现
  • 从嵌套文件夹导入模块[重复]

    这个问题在这里已经有答案了 我有这样的文件夹结构 main folder done test1 init py check py init py class Tries object def init self print Test 检查
  • 如何在 iframe 中查找 div

    我正在尝试使用 jquery 在 iframe 中查找 div 有没有比我下面使用的方法更好的方法 Iframe contents find MyDiv function atmslidein customer ready function
  • Flex 的 FXG 编辑器

    我见过的唯一适用于 Flex 的 FXG 编辑器是由 7jigen 制作 在线工作或 作为 Flex 应用程序 有人知道另一种吗 我认为它可以在 Illustrator 中完成 但这并没有真正提供简单的导出到 Flex 类型选项 只是给出坐
  • 使用方法引用进行混淆后,会出现 NoSuchMethodError 崩溃

    编译 proguard之前的源代码 public class IntentSession extends BaseIntentSession Override public void onResume super onResume mExe
  • 如何检索模块的路径?

    我想检测模块是否已更改 现在 使用 inotify 很简单 您只需要知道要从中获取通知的目录即可 如何在 python 中检索模块的路径 import a module print a module file 实际上会给你加载的 pyc 文
  • Delphi TPath.GetTempPath 结果被裁剪

    我正在使用 Delphi 2010 我的程序想要获取系统的临时路径 我正在使用 TPath GetTempPath 并且一切正常 至少对于我和我的同事来说 但在某些客户计算机上 此方法返回 当然 不存在的裁剪路径 我发现问题似乎是对 Get
  • 我可以在 Google App Engine(标准环境)中使用 Goroutines 吗?

    下面的例子似乎可行 但是使用安全吗 我的目标是进行一些非常轻的后台处理 而实际的任务队列作业感觉太繁重 func MyHandler w http ResponseWriter r http Request go func do somet
  • REST 复杂/复合/嵌套资源 [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我正在尝试解决基于 REST 的 API 中的概念的最佳方法 不包含其他资源的扁平资源没有问题 我遇到麻烦的是复杂的资源 例如 我有一本漫画书的资源 ComicBook上面有各种
  • 不平衡数据和加权交叉熵

    我正在尝试使用不平衡数据训练网络 我有 A 198 个样本 B 436 个样本 C 710 个样本 D 272 个样本 我已经阅读了有关 weighted cross entropy with logits 的内容 但我找到的所有示例都是用
  • TableRow 跨度不适用于动态添加的行

    我在将行动态添加到滚动视图内的 TableLayout 时遇到以下问题 这些行遵循以下模式 第 1 行 单元格横跨整个表格第 2 行 两个单元格第 3 行 单元格横跨整个表格 N 行 两个单元格 问题在于 具有一个单元格跨越该行的行实际上根
  • 重写 ApplicationRecord 初始化,是个坏主意吗?

    我正在创建一个foo像这样的对象 foo Foo new foo params foo bar Bar where name baz first or create 但我还需要其他对象来执行此操作 所以 我想到了重写Foo初始化方法执行如下
  • 如何在运行时从一个应用程序切换到另一个应用程序

    是否有可能使用 Appium 在运行时从一个应用程序切换到另一个应用程序 Thanks 终于我找到了准确的答案 希望它对某些人有用 source https www linkedin com grp post 6669152 6027319
  • 如何在执行某个动作后自动触发回车键按下事件?

    I m writing some unit test in my web apps and I want to automatically trigger an Enter key pressed event from my page af
  • 是否有维护插入顺序的 IdentityHashMap 实现?

    我需要一个 HashMap 1 通过对象引用匹配键 并且 2 迭代时保持插入顺序 这些功能分别在 IdentityHashMap 和 LinkedHashMap 中实现 有没有办法获得适合我需要的数据结构 Java 标准或第 3 方库 如
  • Angular 6 中 MatDialog 关闭且数据库中的数据更新后如何刷新组件?

    我正在学习 Angular 6 的 MEAN 堆栈应用程序 在这里 我想在添加新的客户端 汽车 司机 预订或更新新的客户端 汽车 司机 预订后刷新组件 但是添加新值后 显示所有值的组件不会更新或刷新 当时无法看到当前值 但是当我在组件之间路