【问题标题】:Listening to window events on Typescript (angular2)在 Typescript (angular2) 上监听窗口事件
【发布时间】:2016-08-09 11:33:49
【问题描述】:

我正在尝试从 angular2 应用程序中收听 window 上的事件,用打字稿编写。我也在使用 jquery(通过typings 添加)。

我想收听的事件是由一个外部库添加的,我在 index.html 上的<script> 标记中添加了该库。如果我在 index.html 上的 window 添加一个监听器,它可以正常工作:

<!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>

但如果我尝试在我的 angular2 应用程序中监听这些相同的事件,它不会:

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 doesn't seem to work. I never get notified about 
   // 'authenticatedUser' events on `window`
   $((<any>window)).on('authenticatedUser', function(e) {
     console.log('fuuuu');
   });


   // this triggers events on `window`
   (<any>window).myNamespace.start({
      scopeName: null,
      canClose: false,
      returnUrl: 'http://localhost:8080/loggedIn'
    });
  }

  constructor(private api: ApiService) { }
}

这是从 angular2 应用程序中将事件处理程序附加到窗口的正确方法吗?我觉得一定有更好的方法。

【问题讨论】:

  • 您尝试过 HostListener 吗??

标签: javascript jquery angular typescript


【解决方案1】:

这是从 angular2 应用程序中将事件处理程序附加到窗口的正确方法吗

如果它适用于 JavaScript,它应该适用于 TypeScript。因此,我将要向您展示的内容不会解决这个问题。

但是不要听这样的窗口事件,因为 Angular 会推荐类似的东西

host: {
    '(window:resize)': 'onResize($event)'
}

【讨论】:

    猜你喜欢
    • 2013-10-20
    • 2017-02-21
    • 1970-01-01
    • 2017-08-13
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多