首页 > 解决方案 > 在Angular中的不同组件上有组件保存按钮触发动作吗?

问题描述

我有一个使用 NGPrime 数据表的角度组件....当用户选择一行时,他们会得到一个弹出组件,让他们编辑数据....在他们编辑数据后,他们可以单击“保存”按钮。如何将保存按钮单击操作发送到带有数据表的组件,以便触发数据刷新?

标签: angularprimeng

解决方案


你有几种方法。

如果它们是不相关的组件,那么

通用服务

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}    
}

在 appmodule 中放入提供者

providers:[ShareService ]

在组件中放入构造函数

constructor(private shareService: ShareService  ){}

从第一个组件发送喜欢

this.shareService.setParam('Sending param');

从第二个组件收到类似

 this.shareService.sharedData.subscribe(data=> { console.log(data); })

路由方法

您可以将参数放入路由器并发送。您可以将路由器设置为参数,就像您的 routing.ts

{ path: 'component/:param', component: RelatedComponent },

然后在组件中你想让它像ActiveRoute构造函数中的导入一样调用

constructor(private route: ActivatedRoute){}

并得到喜欢

this.route.snapshot.paramMap.get('param')

或者如果您不想在路线中显示参数,您可以像下面的代码一样发送状态

this.router.navigate(['your_component_url'], {state: { param: 'data you send' } });

在构造函数中读取状态this.router.getCurrentNavigation().extras.state.param;

储存方法

您可以设置为 localStorage 或 sessionStorage 然后从另一个组件的存储中获取。

localStorage.setItem("param","parameter")

localStorage.getItem("param")

如果它们是父子组件,那么你也可以在上面做,而且也很容易使用

@输入法

<your_child_component param="{{ parameter}}"></your_child_component>

在子组件中getlike

@Input param;

推荐阅读