首页 > 解决方案 > 类型'可观察的' 缺少类型 'string[]' 的以下属性:length、pop、push、concat 和另外 25 个

问题描述

我正在尝试使用角度材料自动完成,并且在尝试从数据库中评估数据时,它给了我这个错误。“Observable”类型缺少“string[]”类型的以下属性:length、pop、push、concat 等 25 个。

我的组件.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));
}

我的服务.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>

标签: angulartypescriptangular-materialobservableangular8

解决方案


订阅的数据不应该是 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");
}

或者让我知道您是否需要可观察的字符串数组...希望它可以帮助您:)


推荐阅读