从API搜索而不提交Angular 2

时间:2018-01-23 13:10:35

标签: angular

我正在为Marvel API做一些应用

https://developer.marvel.com/

请求是我需要搜索输入,当用户搜索某些值以显示Marvel API的结果时,唯一的问题是我不想按钮和调用点击转到API并返回结果。当用户输入内部输入时,它必须返回结果。当我有按钮时,我知道如何制作它,但是当用户输入内部输入时,有人可以帮我制作它。这就是我现在所拥有的简单按钮

应用,module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { Ng2OrderModule } from 'ng2-order-pipe';
import { Md5 } from 'ts-md5/dist/md5';
import { CharactersService } from './characters/characters.service';
import { NgxPaginationModule } from 'ngx-pagination';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { CharactersListComponent } from './characters/characters-list/characters-list.component';

@NgModule({
    declarations: [
        AppComponent,
        CharactersListComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        AppRoutingModule,
        Ng2SearchPipeModule,
        Ng2OrderModule,
        NgxPaginationModule,
    ],
    providers: [CharactersService, Md5],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    bootstrap: [AppComponent]
})
export class AppModule { }

characters.service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Md5 } from 'ts-md5/dist/md5';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class CharactersService {
    private _marvelCharacterUrl: string = "https://gateway.marvel.com:443/v1/public/characters";
    private _publicKey: string = "c4b5296bc35888971631d22848916410";
    private _privateKey: string = "fddd97e16368b2fee706a1f6de69f30f191467d3";
    constructor(private _httpService: HttpClient, private _md5: Md5) { }
    private getHash(timeStamp: string): string {
        let hashGenerator: Md5 = new Md5();
        hashGenerator.appendStr(timeStamp);
        hashGenerator.appendStr(this._privateKey);
        hashGenerator.appendStr(this._publicKey);
        let hash: string = hashGenerator.end().toString();
        return hash;
    }
    private getTimeStamp(): string {
        return new Date().valueOf().toString();
    }    
    getAllCharacters() {
        let timeStamp = this.getTimeStamp();
        let hash = this.getHash(timeStamp);
        let requestUrl = this._marvelCharacterUrl + "?orderBy=name" + "&ts=" + timeStamp + "&apikey=" + this._publicKey + "&hash=" + hash;
        return this._httpService.get(requestUrl);
    }

    getCharacterByName(name: string) {
        let timeStamp = this.getTimeStamp();
        let hash = this.getHash(timeStamp);
        let requestUrl = this._marvelCharacterUrl + "?orderBy=name" + "&nameStartsWith=" + name + "&ts=" + timeStamp + "&apikey=" + this._publicKey + "&hash=" + hash;
        return this._httpService.get(requestUrl);
    }

}

字符-list.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { CharactersService } from '../characters.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
    selector: 'app-characters-list',
    templateUrl: './characters-list.component.html',
    styleUrls: ['./characters-list.component.css']
})
export class CharactersListComponent implements OnInit {
    private characters: any = [];

    constructor(private charactersService: CharactersService, private router: Router,
        private activatedRoute: ActivatedRoute ) { }

ngOnInit() {
    this.getCharacters();
}

private getCharacters(){
    this.charactersService.getAllCharacters()
        .subscribe(characters => {
            this.characters = characters;    
        });
}
    private getCharactersSearch(query: string) {
        this.charactersService.getCharacterByName(query)
            .subscribe(characters => {
                this.characters = characters;
            });
    }
}

字符-list.component.html

<header>
  <nav class="navbar navbar-default">
    <a class="navbar-brand" href="#">Application</a>
  </nav>
</header>

<div class="container">
  <div class="row">
    <nav class="navbar">
      <input class="form-control" type="text" name="search" #searchTerm>
      <button (click)="getCharactersSearch(searchTerm.value)">Search</button>
    </nav>
    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Name
          </th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let character of characters.data.results | orderBy: key : reverse | paginate: { itemsPerPage: 10, currentPage: p }">
          <td>{{character.id}}</td>
          <td>{{character.name}}</td>
        </tr>
      </tbody>
      <pagination-controls (pageChange)="p = $event"></pagination-controls>
    </table>
  </div>
</div>

3 个答案:

答案 0 :(得分:2)

在输入(keyup)="getCharactersSearch(searchTerm.value)"上使用<nav class="navbar"> <input class="form-control" type="text" name="search" #searchTerm (keyup)="getCharactersSearch(searchTerm.value)"> </nav>

<nav class="navbar">
    <input class="form-control" type="text" name="search" #searchTerm  (keyup)="searchTerm.value.length ? getCharactersSearch(searchTerm.value) : getCharacters()">
</nav>

当用户开始输入时会调用api

Here are the official docs

更新

Socket

答案 1 :(得分:0)

这是更好的方法,为什么这更好,请阅读评论:

模板面:

<input #search type="text" name="search" />

组件方:

@ViewChild('search') search: ElementRef;
ngOnInit() {
    let inputElm = this.search.nativeElement;
    /**
    * Observable.fromEvent :
    * To prevent call on each keyup event , this will wait for 200ms while user 
    * will be typing , just to reduce load over server and to reduce api calls
    */
    Observable.fromEvent(inputElm, 'keyup').debounceTime(200).subscribe(res => {
        if (inputElm.value.length > 0) {
            console.log(inputElm.value);
        } else {
            console.log('Empty');
        }
    });
}

<强> WORKING DEMO

答案 2 :(得分:0)

为什么不使用自动填充功能。

Doc for autocomplete