2017-02-17 39 views
0

我正在构建一个交互式的web应用程序,我的网页的核心部分是一个角度组件,interactionStage.component,它包含打字稿类InteractionStage.ts。后者,因为它的名字所暗示的,是一个图形化的“舞台”,用户可以互动,它侦听并响应很多这是在舞台的背景下重要的鼠标事件。发送angular2事件从一个打字稿类是**不** **一个角度组件

省略不必要的细节,我interactionStage.component看起来是这样的:

@Component({ 
    selector: 'interaction-stage', 
    templateUrl: './interactionStage.component.html', 
    styleUrls: ['./interactionStage.component.css'], 
}) 
export class InteractionStage.component implements OnInit { 
    private stage : InteractionStage; 

    constructor(){ 
     this.stage = new InteractionStage(); 
    } 

    catchImportantEvent($event) { 
     console.log($event); 
     //Do stuff with the event data 
    } 
} 

没有太多的展示,只是给大家一些情况下,我国InteractionStage类看起来是这样的:

export class InteractionStage { 

    constructor(){ 
     //initialize important stuff here 
    } 

    public emitImportantEvent() { 
     //TODO: emit an event so that interactionStage.component receives it 
    } 
} 

鉴于的InteractionStage性质,需要能够当一个动作发生在它,例如,通知的东西的用户显示一个模式,或改变DOM发射事件。这些事件需要由InteractionStage.component接收,并且将来可能需要由页面上的其他角度组件接收。

我面对的是从InteractionStage发射这些事件的问题。我知道如何使用角度组件发射和捕获事件,通过使用@Output表示法。作为一个在黑暗中刺,我试图用我的InteractionStage类:

import { Output, EventEmitter } from '@angular/core'; 

export class InteractionStage { 

    @Output importantEvent: EventEmitter<any> new EventEmitter(); 

    constructor(){ 
     //initialize important stuff here 
    } 

    public emitImportantEvent() { 
     var importantData = "here is a very important string"; 
     this.importantEvent.emit(importantData); 
    } 
} 

然后我试图在我的InteractionStage.component赶上这个事件是这样的:

<interaction-stage (importantEvent)=catchImportantEvent($event)></interaction-stage> 

但是,绝对没有任何反应。没有收到事件并且没有任何内容记录到控制台。

我做得不对,或者是什么,我试图做不可能的?如果无法完成,我还能如何从打字稿文件发送一个事件并让它被一个角度组件捕获?

我知道我可以传递的InteractionStage.component参考到的InteractionStage构造,但我认为这是一个代码味道 - 耦合是unneccesary。交互阶段不应该知道持有它的角度分量。

回答

2
@Component({ 
selector: 'interaction-stage', 
    templateUrl: './interactionStage.component.html', 
    styleUrls: ['./interactionStage.component.css'], 
}) 
export class InteractionStageComponent implements OnInit { 
    private stage : InteractionStage; 
    @Output myEmitter: EventEmitter<any> = new EventEmitter<any>(); 

    constructor(){ 
     this.stage = new InteractionStage(myEmitter); 
    } 

    catchImportantEvent($event) { 
     console.log($event); 
     //Do stuff with the event data 
    } 
} 

export class InteractionStage { 

    constructor(private myEmitter: EventEmitter<any>){ 
     //initialize important stuff here 
    } 

    public emitImportantEvent() { 
     this.myEmitter.emit("my data"); 
     //TODO: emit an event so that interactionStage.component receives it 
    } 
} 

我也改变InteractionStage.component到InteractionStageComponent因为angularCLI产生这样说,这让我承担其做法

相关问题