角度2材质自动完成组件不显示项目

时间:2017-07-13 14:54:59

标签: angular autocomplete

我正在尝试使用Angular Material开发自动完成样本。我已经完成了几个样本并且工作正常,但这次列表没有显示内容,如下面的屏幕截图所示。 enter image description here

列表中有些项目但没有显示,当我选择组件内部的项目时也是空的。 这是我的代码:

网站类:

export class Sites {
    siteID:number;
    siteURL:string;
    constructor(siteID:number, siteURL:string)
    {
        this.siteID = siteID;
        this.siteURL = siteURL;
    }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule,FormControl } from '@angular/forms';
import {MdInputModule,MdAutocompleteModule} from '@angular/material';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { MaterialModule } from '@angular/material';
import 'hammerjs';

import { AppComponent } from './app.component';
import { SiteAutoCompleteComponent } from './site-auto-complete/site-auto-complete.component';
import { SpWebApiService } from './sp-web-api.service';
import { ConfigService } from './utils/config.service';

@NgModule({
  declarations: [
    AppComponent,
    SiteAutoCompleteComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule,
    BrowserAnimationsModule,MdInputModule,MdAutocompleteModule,MaterialModule
  ],
  providers: [SpWebApiService, ConfigService],
  bootstrap: [AppComponent]
})
export class AppModule { }

服务

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import { Sites } from './sites';
import { ConfigService } from './utils/config.service';

@Injectable()
export class SpWebApiService {

  apiRoot: string = '';

  constructor(private http: Http, private configService: ConfigService) {
    this.apiRoot = configService.getApiURI();
  }

 //With Observable 
  getSitesByName(siteUrl: string): Observable<Sites[]> {
    // debugger;
    console.log('GetSitesByName Service call starting... SiteUrl: ' + siteUrl);
    let apiURL = `${this.apiRoot}Sites/GetSitesByName/${siteUrl}`;
    return this.http.get(apiURL)
      .map(res => 
      {
        console.log('GetSitesByName result: ' + res.text());
        return res.json().results.map(item => 
          {
            return new Sites(
              item.siteID,
              item.siteURL
            );
          }
        )
      })
      .catch(error => {
        console.log(error);
        return Observable.throw(error.json());
      });
  }

}

组件:

import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule,FormControl, FormsModule } from '@angular/forms';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/startWith';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { SpWebApiService } from '../sp-web-api.service';
import { Sites } from '../sites';

@Component({
selector: 'app-site-auto-complete',
templateUrl: './site-auto-complete.component.html',
styleUrls: ['./site-auto-complete.component.css']
})
export class SiteAutoCompleteComponent implements OnInit {

searchForm: FormGroup;

private sites: Observable<Sites[]>;
private filteredSites: Observable<Sites[]>;

constructor(private spWebApiService: SpWebApiService, private fb: FormBuilder) { 
  this.createForm();

  this.ServiceCallConf();
}

ServiceCallConf()
{
  // this.siteURL = new FormControl();
  this.sites = this.searchForm.get('siteURLInput').valueChanges
  // .startWith(null)
  .debounceTime(1000)
  .distinctUntilChanged()
  .do(_ => {
    // if ( this.SearchForm.get('siteURL').value.length > 0)
    //   this.loaderService.display(true);
    // else
    //   return false;
  })// .do(_ => this.loading = true)
  .switchMap(searchTerm => this.filterSites(searchTerm)) //switchMap automatically unsubscribes from any previous observable when a new event comes down the stream.
  .do(_ => 
    {
      // this.loaderService.display(false);// this.loading = false; 
      console.log(this.sites); 
      // console.log(JSON.parse(JSON.stringify(this.Sites || null )));
    })
  .catch(this.handleSiteServiceError);
}
private handleSiteServiceError(error: Response) {
  // this.loaderService.display(false);
  return Observable.throw('handleSiteServiceError'); 
}

filterSites(siteURL: string) {
  console.log('filterSites starting...' + siteURL);
  // debugger;
  if(siteURL=='')
    return;

  this.filteredSites = this.spWebApiService.getSitesByName(siteURL);
  console.log('filteredSites:' + this.filteredSites);
  return this.filteredSites;
}

selectedSite:Sites;
displayFn(site: Sites): string {
  // debugger;
  this.selectedSite = site;
  console.log('displayFn: ' + this.selectedSite);
  return site ? site.siteURL : "";
}

createForm() {
  this.searchForm = this.fb.group({
    siteURLInput: ['', Validators.required]
  });
}

ngOnInit() {

}
}

HTML:

<form [formGroup]="searchForm" novalidate>
  <!--(ngSubmit)="getWeather(WeatherSearchForm)" -->
  <div class="form-group">
    <div class="container">
      <div class="row">
        <div class="col-md-6">
          <md-input-container>
            <input mdInput placeholder="Type Domain Name..." [mdAutocomplete]="auto" 
            class="form-control validate filter-input" formControlName="siteURLInput">
          </md-input-container>
          <md-autocomplete #auto="mdAutocomplete" md-input-name="autocompleteField" 
          required md-input-minlength="2" md-input-maxlength="50"
            md-select-on-match [displayWith]="displayFn">
            <md-option *ngFor="let site of sites | async" [value]="site">
              {{ site.siteURL }}
            </md-option>
          </md-autocomplete>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6">
          <button (click)='LoadSiteInfo(SearchForm)' class="btn btn-success" 
          [disabled]="!searchForm.valid">Go</button>
        </div>
      </div>
    </div>
  </div>
</form>

1 个答案:

答案 0 :(得分:0)

经过一整天的挖掘,终于找到了问题。 它与区分大小写有关。 Web API返回SiteID而不是siteID。 所以我改变了我的代码:

return res.json().results.map(item => 
          {
            return new Sites(
              item.siteID,
              item.siteURL
            );
          }
        )

到此:

return res.json().results.map(item => 
          {
            return new Sites(
              item.SiteID,
              item.SiteUrlShort
            );
          }
        )

并且有效。