如何在 Angular2 RC5 打字稿中调用共享指令的方法?

How do I call shared directive's method in Angular2 RC5 typescript?

我的代码中有多个组件应该使用的自定义指令。我在我的 app.module 中注册了它,因此可以在我的模板中使用它。

但我的问题是我看不到从组件代码中调用此指令的方法,因为它不再在 directives: [] 中导入和注册它?

例如 在这里,当我不共享指令时,它被用作

    import { Modal } from '../bootstrap';
    @Component({
        templateUrl: '.....html',
        directives: [Modal]
    })
    export class MyComponent {
            constructor(private modal: Modal) {
            this.modal.show();
        }
    }

但是当我将这些组件提取到单独的模块并将该指令移动到共享模块时,import ..directives: [...] 消失了,我无法注入 private modal: Modal 来调用它方法show。如果我保留它们,我会收到 Error: Type Modal is part of the declarations of 2 modules: ... 错误消息。

将其添加到您的 AppModule 中的 [providers]

providers: [Modal]

然后你需要在应该使用它的组件中导入该服务,它就会工作,不需要将它添加为指令,例如:

import { Modal } from '../bootstrap';

然后您可以将其添加到构造函数中:

constructor (private modal: Modal)

现在您可以使用该服务了:

this.modal.show()

编辑:

更新了答案以匹配您提供的代码。