Trying to capture events on the window
object from an Angular 2 application written in TypeScript. Additionally, jQuery (imported via typings
) is being used.
The desired events are generated by an external library included using <script>
tags in index.html. When a listener is added to window
in index.html, everything works as expected:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="http://my-host/front-libs/jquery/1.8.3/jquery-1.8.3.min.js"></script>
<script src="https://my-host/my-external-lib.min.js"></script>
<title>Angular 2 App | ng2-webpack</title>
<link rel="icon" type="image/x-icon" href="/img/favicon.ico">
<script>
// this works!!
$(window).on('authenticatedUser', function(e) {
console.log('ok.');
});
</script>
<base href="/">
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
However, attempting to listen for the same events within the Angular2 app does not yield the desired outcome:
import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { ApiService } from './shared';
import '../style/app.scss';
/*
* App Component
* Top Level Component
*/
@Component({
selector: 'my-app', // <my-app></my-app>
providers: [ApiService],
directives: [...ROUTER_DIRECTIVES],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
url = 'https://github.com/preboot/angular2-webpack';
ngOnInit(){
// This method doesn't seem effective. Notifications for
// 'authenticatedUser' events on `window` are never received
$((<any>window)).on('authenticatedUser', function(e) {
console.log('fuuuu');
});
// This successfully triggers events on `window`
(<any>window).myNamespace.start({
scopeName: null,
canClose: false,
returnUrl: 'http://localhost:8080/loggedIn'
});
}
constructor(private api: ApiService) { }
}
Is this the proper approach for attaching event handlers to the window object from within an Angular 2 app? There might be a more efficient way to accomplish this task.