类型'Observable <string []>'缺少类型'string []'的以下属性:length,pop,push,concat和另外25个

时间:2019-11-11 13:26:35

标签: angular typescript angular-material observable angular8

我正在尝试使用角度材料自动完成功能,并且在尝试从数据库中获取数据时,出现了这个错误。 类型'Observable'缺少类型'string []'的以下属性:length,pop,push,concat和另外25个。

我的component.ts

export class SearchComponent implements OnInit {
constructor(private reservationService: ReservationService, private searchService: SearchService){}

 location;
 CheckIn;
 AdultNumber;
 myControl = new FormControl();
 options: string[] = ['One', 'Two', 'Three'];
 filteredOptions: Observable<string[]>;
 regions: string[];

ngOnInit() {
  this.filteredOptions = this.myControl.valueChanges
  .pipe(
    startWith(''),
    map(value => this._filter(value))
  );

  this.reservationService.getRegions().subscribe((data: Observable<string[]>)=>{
    console.log(data);
    this.regions= data;  // ERROR IS HERE ERROR ERROR ERROR
  }) 
  /* this.reservationService.getRegions().subscribe(sa => console.log(sa)); */

}
getregionlist(){

  console.log(this.location,"location")
  console.log(this.CheckIn,"checkindate")
  console.log(this.AdultNumber,"AdultNumber")
  console.log(this.array,"array")

}

private _filter(value: string): string[] {
  const filterValue = value.toLowerCase();

  return this.regions.filter(option => option.toLowerCase().includes(filterValue));
}

我的service.ts

getRegions(){
    return this._http.get("https://localhost:44389/api/locations");
 }

我的html

<mat-form-field class="example-full-width">
        <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
            {{option}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>

1 个答案:

答案 0 :(得分:1)

订阅的数据不应为Observable类型,您已经订阅了Observable类型的方法。...仅按如下方式使用...

在组件中:

 this.reservationService.getRegions().subscribe((data)=>{
    console.log(data);
    this.regions= data;  
 }) 

服务中:

getRegions():Observable{
    return this._http.get("https://localhost:44389/api/locations");
}

上面的方法可以很好地工作...但是,如果您想显式定义...,它应该如下所示。 订阅的数据不应为Observable类型,您已经订阅了Observable类型的方法。...仅按如下方式使用...

在组件中:

 this.reservationService.getRegions().subscribe((data:string[])=>{
    console.log(data);
    this.regions= data;  
 }) 

服务中:

getRegions():Observable<string[]>{
    return this._http.get("https://localhost:44389/api/locations");
}

或者让我知道您是否需要在这里观察字符串数组...希望对您有所帮助:)