如何在Angular 2中获取输入的输入值的API响应

时间:2017-03-13 21:25:19

标签: angular typescript

我有一个API,它接受用户输入(在这种情况下是用户名)并返回用户名可用性的可用性。

.Html文件

Enter username: <input type="text"
id="username"
placeholder="enter username"
[(ngModel)]="user.username"
name="username">
<button (click)="getUsername()">Click me</button>

在上面的代码中输入用户名值为#username

Component.ts

import { Component, OnInit} from '@angular/core';
import { HttpService } from "./http.service";
import { Response } from '@angular/http';
import 'rxjs/add/operator/map';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[HttpService]
})
export class AppComponent implements OnInit{
constructor(private httpService: HttpService) {}

user = {
  username: ''
}

inputvalue:string  = this.user.username;

ngOnInit() {
  this.httpService.getData()
  .subscribe(
    (inputdata: Response) => console.log(inputdata.json())
  )
}

}

在输入值&#39;

中存储输入值

服务

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { AppComponent } from './app.component'

@Injectable()
export class HttpService {

  constructor(private http: Http, private appComponent: AppComponent) { }
getData(){
  return this.http.get("MyAPIurl/"+this.appComponent.inputvalue);
}

}

在服务上我想传递输入值并将其附加到我的API网址,以便每当用户输入用户名时我都可以得到响应。

有人可以纠正我,让我知道它是如何运作的!

PS:我对Angular2很新!

1 个答案:

答案 0 :(得分:0)

让您的HttpService更可重复使用:

HttpService.getData必须接受参数

在订阅之前将您的数据转换为json

    import { Component, OnInit} from '@angular/core';
    import { HttpService } from "./http.service";
    import 'rxjs/add/operator/map';


    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
      providers:[HttpService]
    })
    export class AppComponent implements OnInit{
    constructor(private httpService: HttpService) {}

    user = {
      username: ''
    }

    inputvalue:string  = this.user.username;

    ngOnInit() {

    }

    getUsername(){
          this.httpService.getData(this.inputvalue)
              .subscribe((inputdata: any) => {
                   console.log(inputdata);
              });

    }

}

HttpService的:

mport { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import { AppComponent } from './app.component'

@Injectable()
export class HttpService {

  constructor(private http: Http) { }
getData(inputValue: string){
  return this.http
             .get("MyAPIurl/"+inputvalue)
             .map(data: Response => data.json());
}

}

注意:为了使您的代码更具可读性,请将HttpService重命名为DataService

相关问题