2017-02-09 78 views
1

我正在建立一個簡單的輸入類型的文本,其中一個Observable對象鏈接到它的關鍵事件。Angular2 Observable與RxJS沒有錯誤,但沒有發生事件

我正在使用Angular2 final(「@ angular/core」:「〜2.1.1」和「rxjs」:「5.0.2」)。

這裏是我的app.component.ts:

import {Component} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
     <input id="search" type="text" class="form-control" placeholder="Search..." > 
    ` 
}) 

export class AppComponent { 
    constructor(){ 
     var keyups = Observable.fromEvent($("#search"), "keyup"); 
     keyups.subscribe(data => console.log(data)); 
    } 
} 

當我按下鍵,沒有出現在控制檯上,所以看起來該事件還沒有被解僱或觀察者在看別處。 缺什麼?

在此先感謝

回答

2

我想你應該嘗試移動兩線,是在構造函數中ngAfterViewInitMethod:

import {Component, AfterViewInit} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/observable/fromEvent'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
     <input id="search" type="text" class="form-control" placeholder="Search..." > 
    ` 
}) 

export class AppComponent implements AfterViewInit { 
    constructor(){ 

    } 
    ngAfterViewInit() { 
     var keyups = Observable.fromEvent($("#search"), "keyup"); 
     keyups.subscribe(data => console.log(data)); 
    } 
} 

但要小心,你也需要保持一個引用您的當您的組件網絡將被刪除時訂閱未寫入。

我不認爲這是執行你想要的「角色方式」。

我認爲最好是將輸入的「keyup」事件綁定到組件的某個方法。

@Component({ 
    selector: 'my-app', 
    template: ` 
     <input (keyup)="onKeyUpOnInput($event)" type="text" class="form-control" placeholder="Search..." > 
    ` 
}) 

export class AppComponent implements AfterViewInit { 
    constructor(){ 

    } 
    onKeyUpOnInput(data){ 
     console.log("Key up"); 
    } 
} 
+0

感謝您的回答!我已經嘗試了第一個解決方案,它的工作原理完全同意你這樣一個事實,即它不是執行我想要的角色方式,但是它是從Angular2的Udemy課程中引入rxjs的一個示例:)但是將這兩行保存在構造函數中,是否有可能使它工作? –

+0

我不這麼認爲。在構造函數中,您的輸入元素不存在。 –