2017-06-26 71 views
0

我有一個 app.component.html從部件將數據發送到服務文件在角2

<input type="text" [(ngModel)]="keystroke"> 
{{keystroke}} <!-- prints out each keystroke --> 

而一個app.component.ts

import { Component } from '@angular/core'; 
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
    keystroke = ''; 
} 

這成功打印出我輸入到我的搜索框中的每個擊鍵值。

不過,我想的按鍵值發送到getResults()功能在我task.service.ts(下面的代碼),這樣我可以使用擊鍵值api電話。

import { Injectable } from '@angular/core'; 
import { Http, Headers } from '@angular/http'; 
import 'rxjs/add/operator/map'; 
@Injectable() 
export class TaskService { 
    constructor(private http: Http) { 
    console.log("Task service initialized..."); 
    } 
    //get our result for each keystroke, return it as an observable (json) 
    getResults() { 
    return this.http.get('http://localhost:8080/api/KEYSTROKES') 
     .map(res => res.json()); 
    } 
} 

但是,我無法弄清楚如何做到這一點。在app.component.html我可以使用{{keystroke}},但引用我的task.service.ts中的擊鍵值似乎並不那麼簡單。

如何將我的按鍵數據發送到我的task.service.ts,以便我可以運行我的api調用?

此外,我正在嘗試創建一個Angular 2應用程序「正確的方式」,所以所有的批評都是值得歡迎的。

回答

0

綁定一個事件處理您的輸入

<input (ngModelChange)="getResults($event)" ...> 

或者

<input (keyup)="getResults($event)" ...> 

https://angular.io/guide/user-input#get-user-input-from-the-event-object

+0

感謝您的評論!我將如何定義html中的getResults?我目前有'''input type =「text」[(ngModel)] =「keystroke」(ngModelChange)=「getResults($ event)」>'''但是當我運行這個時,getResults只是未定義。 – user3335607

+0

哦,getResults()需要在你的@Component中,(事件處理程序應該重命名爲onKeyUp())。這會打電話給你的服務。 – theRemix

相關問題