如何在Angular中通过http请求获取自动搜索的数据?

时间:2018-02-23 01:57:47

标签: ajax angular httprequest

您好我正在开发Angular JS 5中的Web应用程序。我正在尝试完成自动搜索功能。我能够使用静态值。现在我正在尝试从API调用中获取数据。以下是我的代码。

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

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { TypeaheadMatch } from 'ngx-bootstrap/typeahead';


    @Component({
      selector: 'demo-typeahead-async',
      templateUrl: './async.html'
    })
    export class DemoTypeaheadAsyncComponent {
      asyncSelected: string;
      typeaheadLoading: boolean;
      typeaheadNoResults: boolean;
      dataSource: Observable<any>;
      statesComplex: any[] = [
        { id: 1, name: 'Alabama', region: 'South' },
        { id: 2, name: 'Alaska', region: 'West' },
        {
          id: 3,
          name: 'Arizona',
          region: 'West'
        },
        { id: 4, name: 'Arkansas', region: 'South' },
        { id: 5, name: 'California', region: 'West' },
        { id: 6, name: 'Colorado', region: 'West' }
    ];

      constructor() {
        this.dataSource = Observable.create((observer: any) => {
          // Runs on every search
          observer.next(this.asyncSelected);
        }).mergeMap((token: string) => this.getStatesAsObservable(token));
      }

      getStatesAsObservable(token: string): Observable<any> {
        let query = new RegExp(token, 'ig');

        return Observable.of(
          this.statesComplex.filter((state: any) => {
            return query.test(state.name);
          })
        );
      }

      changeTypeaheadLoading(e: boolean): void {
        this.typeaheadLoading = e;
      }

      changeTypeaheadNoResults(e: boolean): void {
        this.typeaheadNoResults = e;
      }

      typeaheadOnSelect(e: TypeaheadMatch): void {
        console.log('Selected value: ', e.value);
      }
    }

在上面的代码中,我正在播放this.statesComplex(硬编码数据)。 下面是我的HTML代码。

<pre class="card card-block card-header">Model: {{asyncSelected | json}}</pre>
  <input [(ngModel)]="asyncSelected"
         [typeahead]="dataSource"
         (typeaheadLoading)="changeTypeaheadLoading($event)"
         (typeaheadNoResults)="changeTypeaheadNoResults($event)"
         (typeaheadOnSelect)="typeaheadOnSelect($event)"
         [typeaheadOptionsLimit]="7"
         typeaheadOptionField="name"
         placeholder="Locations loaded with timeout"
         class="form-control">
  <div *ngIf="typeaheadLoading===true">Loading</div>
  <div *ngIf="typeaheadNoResults===true">&#10060; No Results Found</div>

我已经创建了调用API的服务,如下所示。

this.useronboardService.searchUsers(query).subscribe(results => this.filterUsername(query, results), error => this.onUsersSearchDataLoadFailed(error));

我尝试如下。下面的代码对我不起作用。

 getStatesAsObservable(token: string): Observable<any> {
        let query = new RegExp(token, '');
        return Observable.of(
            this.useronboardService.searchUsers(token).subscribe(
                 result => result.filter((user: any) => {
                   return query.test(user.userName),
                        error => console.log(error)
                }))
    );

我想使用上面的服务数据而不是this.statesComplex。我的服务返回包含属性id和用户名的数组。有人可以帮助我做这项工作吗?谢谢。

1 个答案:

答案 0 :(得分:1)

this.useronboardService.searchUsers(token)已经是一个可观察的,所以你不需要将它包装在Observable.of(...)中。只需将结果映射到过滤值即可。

getStatesAsObservable(token: string): Observable<any> {
    let query = new RegExp(token, '');
    return this.useronboardService.searchUsers(token)
        .map(result => result.filter((user: any) => query.test(user.userName)));
}