I am in the process of updating an existing Angular application to utilize Angular 2. One challenge I am facing is opening an OAuth flow in a new pop-up window and then using window.postMessage to send a signal back to the Angular 2 app once the OAuth process is successfully completed.
The current setup in my Angular 2 service looks like this:
export class ApiService {
constructor(private _loggedInService: LoggedInService) {
window.addEventListener('message', this.onPostMessage, false);
}
startOAuthFlow() {
var options = 'left=100,top=10,width=400,height=500';
window.open('http://site/connect-auth', , options);
}
onPostMessage(event) {
if(event.data.status === "200") {
// Use an EventEmitter to notify other components that user has logged in
this._loggedInService.Stream.emit(null);
}
}
}
This is the template that is displayed at the end of the OAuth flow:
<html>
<head>
<title>OAuth callback</title>
<script>
var POST_ORIGIN_URI = 'localhost:8000';
var message = {"status": "200", "jwt":"2"};
window.opener.postMessage(message, POST_ORIGIN_URI);
window.close();
</script>
</head>
</html>
Using window.addEventListener
in this manner seems to disrupt the functionality of the Angular 2 app by losing reference to this
.
So my question is whether it is appropriate to use window.addEventListener or if there is a better alternative than postMessage for communicating back to the Angular 2 app?
** I am relatively new to Angular 2 so any guidance would be greatly appreciated