2016-07-18 101 views
1

我在組件中有一個@Output類型EventEmitter<any>。如果在點擊按鈕後在功能上調用.emit(),輸出將起作用。在這種情況下,我能夠在父組件中捕獲事件而不會出現問題。但是,這實際上只是一個測試措施。當我嘗試做我真正想做的事情,即進行數據庫調用,然後在成功時發出事件時,事件永遠不會從子組件發出,也不會從父組件發出。這裏的代碼一點點地說明我的意思:Angular 2 EventEmitter問題

testOutput() { 
    this.outputEvent.emit({event: 'buttonClick', message: 'Here is some output'}); 
} 

makeAnUpdate(form) { 
    this._service.makeDbCall(data).subscribe(result => { 
     this.variable = result; 
     this.outputEvent.emit({ message: 'Here is a message to pass', success: true }); 
    }); 
} 

我也試着撥打剛剛從下面的功能的認購部分內發出該事件的功能,它仍然沒有工作:

makeAnUpdate(form) { 
    this._service.makeDbCall(data).subscribe(result => { 
     this.variable = result; 
     this.testOutput(); 
    }); 
} 

有沒有其他人有過這個問題?同樣,上面的testOutput函數只有在你調用它時才起作用,但不能從makeAnUpdate函數中起作用。

+1

很難知道沒有看到'this._service.makeDbCall(data)'做了什麼。我假設傳遞給'subscribe(...)'的回調函數沒有被調用。 –

+0

它確實被調用。該調用是對數據庫進行的,然後回到該功能。我當然知道,因爲如果我在那裏的事件發射器之前做一個'console.log','console.log'就可以工作並顯示出來。 – pjlamb12

+0

我假設執行不知何故離開安格拉斯區。我會添加一個答案。 –

回答

1

makeDbCall返回的可觀測值的回調可能跑出Angulars區域。請嘗試

class MyComponent { 
    constructor(private zone:NgZone) {} 
    makeAnUpdate(form) { 
    this._service.makeDbCall(data).subscribe(result => { 
     this.zone.run(() => { 
      this.variable = result; 
      this.outputEvent.emit({ message: 'Here is a message to pass', success: true }); 
     }); 
    }); 
    } 
} 
+0

這與沒有'ngZone.run'的效果相同。一個'console.log'打印出來,數據從數據庫中返回等等,但事件不會被髮射。 – pjlamb12

+0

很難分辨。沒有什麼可以出錯的。我想我們需要一個更完整的例子來展示偵聽事件和發出事件的組件是如何相關的,方法和事件處理程序在哪裏以及如何調用它們。 –

+0

[這是一個要點](https://gist.github.com/pjlamb12/c3f6633008093eb268fd5b2f618c0934),其中的示例文件與真實文件一樣。這非常簡單;我真的不知道我可能提供哪些其他信息。 – pjlamb12