我试图找出一种最简单的方法,当它们不共享父子关系时,将事件从一个 Angular 2 组件传递到另一个组件。
具体来说,我有一个用于打开对话框的组件(单击时会打开一个新组件)。一旦用户单击该新对话框组件上的按钮,我想将该事件的通知发送回原始组件(单击按钮以打开对话框/组件开始),以便我可以触发在那里发挥作用。
以下是原始组件中用于触发对话框打开的代码:
public onResponseSelected(option, selectedService)
{
const primaryEmail = this.getPrimaryEmail();
let currentService = this.selectedService;
let activeList = this.getActiveList();
if (option && option.toString() === 'Follow-up Required')
{
// Create dialog
let dialogRef: MdDialogRef<ResponseProcessComponent>
= this.mdDialog.open(ResponseProcessComponent, {
disableClose: true,
data: {
option: option,
currentService: currentService,
primaryEmail: primaryEmail,
activeList: activeList
}
});
dialogRef = null;
}
}
我在这里“打包”一些数据以作为“数据”的一部分发送到对话框组件。这一切都按预期工作。
现在我只需要一种方法将事件触发器从对话框组件(responseProcessComponent)发送回原始组件。提醒一下,这里没有共享 View ,因此我无法通过 Input() 传递下去,就好像这些组件具有父子关系一样。
我只需要一种方法来触发对话框组件中的事件并将其发送回其他组件。最简单的方法是什么?
最佳答案
您可以使用共享服务并从注入(inject)该服务的任何组件发送通知。
考虑以下因素:
dialog.service.ts
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
@Injectable()
export class DialogService {
public dialog = new BehaviorSubject<string>('Not Clicked');
dialogObservable = this.dialog.asObservable();
changeDialogState (value: string): void {
this.dialog.next(value);
}
}
然后在你的组件中:
reciver.component.ts
要获取对话框状态,请执行以下操作:
constructor(private ds: DialogService) {
this.ds.dialogObservable
.subscribe((dialogState) => {
//add your logic here!! for now I'm just gonna console log the sate of the dialog
console.log(dialogState);
});
}
要为对话框设置新状态,请执行以下操作:
changeDialogState(){
this.ds.changeDialogState('Cliked');
}
并且不要忘记将服务添加到提供数组中,并将组件添加到同一模块的声明数组中,这样就不会出现任何错误。
关于javascript - 将事件向下传递给 Angular 2 应用程序中不是另一个组件的父组件或子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46614139/