类型“Observable<string[]>”缺少类型“string[]”的以下属性:长度、弹出、推送、连接以及其他 25 个属性

Wor*_*mre 5 observable typescript angular-material angular angular8

我正在尝试使用角度材料自动完成,并且在尝试从数据库获取数据时,它给了我这个错误。类型“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));
}
Run Code Online (Sandbox Code Playgroud)

我的服务.ts

getRegions(){
    return this._http.get("https://localhost:44389/api/locations");
 }
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

小智 2

订阅的数据不应该是Observable类型,你已经订阅了Observable类型的方法....只需使用如下...

在组件中:

 this.reservationService.getRegions().subscribe((data)=>{
    console.log(data);
    this.regions= data;  
 }) 
Run Code Online (Sandbox Code Playgroud)

服务中:

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

上面的工作完全没问题...但是如果你想显式定义...它应该像下面这样..订阅的数据不应该是 Observable 类型,你已经订阅了 Observable 类型的方法....只需使用如下所示。 ..

在组件中:

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

服务中:

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

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