1

当对 api 进行异步调用并尝试将数据从 api 绑定到 mat-select 控件时,它没有绑定 bcoz mat-select 已经设置,而结果在一段时间后被获取。谁能告诉我如何解决这个问题

app.component.html

<mat-select appearance=fill>
      <mat-option *ngFor="let city of data | async " [value]="city">{{city}}</mat-option>
    </mat-select>

在 app.component.ts

export class AppComponent implements AfterViewInit {
 
  dataarr: string[] = [];
  
  constructor() {

    this.getDatafromURL(this.dataarr, 'http://localhost:8080/geoserver/tutorial/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=tutorial%3Adistrict&maxFeatures=50&outputFormat=application%2Fjson')
         
  }
  getDatafromURL(data:string[],url:string) {
     
    fetch(url).then(function(response){
      response.json().then(function(result){
        let features = result.features;
        
        features.forEach((element: { properties: { NAME_2: any; }; }) => {
          data.push(element.properties.NAME_2)
        });
        
      })
      
    })
    
  }
4

1 回答 1

1

尝试这个:

ngOnInit(): void {
  this.countryList$ = this.getCountries();
}

getCountries(): Observable<ICountry> {
 return this.http.get<ICountry> 
 ('https://jsonplaceholder.typicode.com/posts');
}

在 ts 文件中:

<ng-container *ngIf="countryList$ | async as countryList">
    <mat-select>
      <mat-option *ngFor="let country of countryList 
        [value]="country">                  
        {{country.name}}
   </mat-option>
 </mat-select>
</ng-container>
于 2022-01-10T07:50:14.853 回答