Issue
I have two angular apps one of which is the parent with and iframe that loads the child app. The HTML is extremely basic:
<div class="first">
<label>{{postedMessage}}</label>
</div>
<div id="second">
<iframe src="http://localhost:4200/" id="displayFrame" title="Compass" width="70%"
float="right" height="750px"></iframe>
</div>
The parent app is listening for a postMessage() event from the child, in this case localhost:4200. I know the postMessage eventListener is working because when the parent does a console.log(JSON.stringify(event)) it logs as expected. The event listener also updates the value of postedMessage at the same time, but it's not updating on the UI. I cannot figure out why. I tried adding a button that updates the value in the same way (except it's not from an event) when the (click) method is called, and that works exactly as expected.
Here is what the typescript looks like:
import { Component, OnInit } from '@angular/core';
@Component({
selector: '',
templateUrl: '',
styleUrls: ['']
})
export class TestComponent {
postedMessage: string = 'This is a test string';
constructor() {
window.addEventListener("message", this.handleEvent, false);
}
handleEvent(event: MessageEvent) {
console.log(JSON.stringify(event));
this.postedMessage = (JSON.stringify(event));
}
}
If anyone has any ideas why this wouldn't be working, it would be very much appreciated! Thanks
To answer carl's answer, I cannot provide the actual child app code. In the most basic fashion though, it would look something like this:
HTML:
<button (click)="postMessage()">Test</button>
Typescript:
postMessage() {
// This is where I'd calculate the data being sent to the parent
data: string; // Some JSON string
window.parent.postMessage(data, this.parentOrigin);
{
This would be the simplest way to show what is happening, but can write up a more in depth example if necessary.
Thanks!
Solution
I think it's because you need to make your variable an Observable stream. Here's what I think would make your code work (NOTE: you will need rxjs installed to use BehaviorSubject
):
postedMessage: BehaviorSubject<string> = new BehaviorSubject<string>('This is a test string');
To make sure the scope of your class component is referenced correctly in the handleEvent, make sure to bind this
:
constructor() {
window.addEventListener("message", this.handleEvent.bind(this), false);
}
Then in the handleEvent
function do this:
handleEvent(event: MessageEvent) {
this.postedMessage.next(JSON.stringify(event));
}
Also use an async pipe for your interpolation:
<label>{{ postedMessage | async }}</label>
Answered By - Ben Brown
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.