HostListener and Angular Universal
I am trying to listen MessageEvent
to posted with postMessage in my Angular 2 component.
My first attempt was simply:
window.addEventListener("message", this.handlePostMessage.bind(this));
And then in ngOnDestroy
:
window.removeEventListener("message", this.handlePostMessage.bind(this));
However, this did not work as expected. If I were to change route and back, two event recorders would be registered.
So I'm trying to decorate the HostListener method instead , but I can't seem to get that to work when using prerendering (Angular Generic with .NET Core using asp-prerender-module
).
@HostListener('window:message', ['$event'])
private handlePostMessage(msg: MessageEvent) {
...
}
This gives me the following error on page load:
Exception: Call to Node module failed with error: Prerendering failed because of error: ReferenceError: MessageEvent is not defined
Is there a workaround for this?
source to share
You are getting this error because MessageEvent is undefined. You must import any file that defines this.
My @HostListeners looks like this:
@HostListener("window:savePDF", ["$event"]) savePDF(event) {
this.savePDFButtonPushed();
}
and you can read more about them here:
https://angular.io/guide/attribute-directives
However, I am currently experiencing the same problem as when going to and from a different route, I now receive two events. And this is using @HostListener. :-( However, I haven't updated Angular in a while (currently using 4.4.6), so maybe they've fixed it since the release.
** Edit: just updated to Angular 5.1.0. @HostListener 'duplicate events' problem remains .: - (
Edit # 2: I also tried using window.addEventListener as you tried and also had the same problem despite using window.removeEventListener in ngOnDestroy ().
This got me to dig a little deeper where I found the code I added to listen for messages from the child iFrame. Do you have something similar in your code?
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to messages from child window ("unsign" and "savePDF") and pass those along as events to Angular can pick them up in its context
eventer(messageEvent,function(e) {
window.dispatchEvent( new Event( e.data ) );
},false);
This was in my page builder. I protected it so that it only runs the first time the page was a constructor and now everything is fine.
source to share