[英]Angular2 modal dialog
Structure of the app: 应用程序的结构:
AppService AppComponent -> HeroComponent -> WeaponComponent -> ButtonComponent AppService AppComponent-> HeroComponent-> WeaponComponent-> ButtonComponent
When someone clicks on the button (ButtonComponent), I would like to open a modal dialog in the AppComponent. 当有人单击按钮(ButtonComponent)时,我想在AppComponent中打开一个模式对话框。
The best way I can think of is making a dialogObservable in the AppService. 我能想到的最好的方法是在AppService中创建一个dialogObservable。 The ButtonComponent sets the observable and the AppComponent listens to it, and shows the dialog when there is a dialog set. ButtonComponent设置可观察对象,AppComponent侦听它,并在有对话框设置时显示对话框。
This already feels a bit messy. 这已经有点混乱了。
But to make it worse, I also need buttons in the Dialog. 但更糟糕的是,我还需要对话框中的按钮。 When someone clicks on the "OK" button, I want to call an action from the WeaponComponent. 当有人单击“确定”按钮时,我想从WeaponComponent调用一个动作。 Which is impossible, as far as I know. 据我所知,这是不可能的。 So what do I do? 那我该怎么办? Create another observable in the service, and listen to it in the WeaponComponent. 在服务中创建另一个可观察的对象,并在WeaponComponent中监听它。
This feels very messy, and I feel there must be a better way. 这感觉很混乱,我觉得必须有更好的方法。 I just can't figure it out. 我只是想不通。
I had a similar problem and I solved it by adding a modal in my root module component, and providing a ModalService
accross my app. 我有一个类似的问题,我通过在根模块组件中添加模态并在ModalService
应用程序中提供ModalService
来解决了该问题。
ModalService
is used as an event dispatcher, to dispatch the modal event. ModalService
用作事件分派器,以分派模态事件。
Exemple with just signatures (to be easy to understand, implementation is not that hard): 仅带有签名的示例(为了易于理解,实现起来并不难):
@Injectable()
export class ModalService{
public registerModal(name:string, onPop:()=>void):void;
public popModal(name:string):void;
}
This way your ModalComponent
can be anywhere (and you can have a lot of modals with different names) and you can pop it from anywhere since you just need to get the ModalService
. 这样,您的ModalComponent
可以在任何地方(并且可以有很多使用不同名称的模式),并且可以从任何地方弹出它,因为您只需要获取ModalService
。
Note that to make this work, you have to use only one instance of ModalService
, so it has to be declared in your module.forRoot()
method. 请注意,要使此工作有效,您只需使用ModalService
一个实例,因此必须在您的module.forRoot()
方法中声明它。
EDIT: 编辑:
To fix the context issue, you can declare your function and store it in a variable, this way: 要解决上下文问题,您可以声明函数并将其存储在变量中,方法如下:
function foo():any{
}
becomes 变成
foo=():any => {
}
then you can pass the callback method to your modal using this.foo
, it will not loose the context. 那么您可以使用this.foo
将回调方法传递给您的模式,这不会丢失上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.