繁体   English   中英

将数据从API绑定到Angular 7中的Dropdown

[英]Bind data from API to Dropdown in Angular 7

我正在尝试从get API填充下拉列表。 我创建了一个服务,并使用可观察对象将数据返回到组件,该组件随后订阅了该服务。 我可以console.log整个数据(在JSON数组中),但是在下拉列表中看不到任何数据。

我想问题是视图是在API数据之前呈现的。 我知道有解决方法,但是我还能尝试什么?

我的问题和代码与以下问题非常相似,并且在我的代码中我已经纠正了一些问题,例如“ Project”是一个数组,但是解决方案不适用于我。 我的代码也没有错误:

下拉列表中未填充API数据

请在下面找到我的代码: TestService.ts

export class TestService {
  public testURL = 'https://test.url';
  constructor(private _http: HttpClient) { }

    getTypes(): Observable<TestModel[]> {
    const headers = new HttpHeaders({'test': 'test1'});
    return this._http.get<TestModel[]>(this.testURL, {headers});
  }
  }

Component.ts

 @Component({
  selector: 'app-header',
  templateUrl: './app-header.component.html',
  styleUrls: ['./app-header.component.css']
})
export class AppHeaderComponent implements OnInit, AfterViewInit {
   testModel: TestModel[];
   isLoaded = false;

  constructor(private _testService: TestService) { }

  getTypeT(): void {
    this._testService.getTypes().subscribe(data => {
      if(data) {
        this.testModel = data;
        this.isLoaded = true;
        console.log(this.testModel);
      }
    } );
  }

  ngOnInit() {
    // fetch all the survey types
    this.getTypeT();
  }

component.html

  <select  class="selectpicker dropdown mt-4 ml-3" id="type" data-live-search="true">
      <option *ngFor="let test of testModel" [value]="test.id">{{test.description}}</option>
   </select>

注意 :我刚刚发现问题似乎出在第三方插件“ selectpicker ”下拉列表中。 您能否提出我可以解决的建议?

您可以尝试使用异步管道。

@Component({
  selector: 'app-header',
  templateUrl: './app-header.component.html',
  styleUrls: ['./app-header.component.css']
})
export class AppHeaderComponent implements OnInit, AfterViewInit {
   testModel: TestModel[];
   isLoaded = false;
   types$;

  constructor(private _testService: TestService) { }

  getTypeT(): void {
    return this._testService.getTypes();
  }

  ngOnInit() {
    this.types$ = this.getTypeT();
  }

的HTML

  <select  class="selectpicker dropdown mt-4 ml-3" id="type" data-live-search="true">
      <option *ngFor="let test of types$ | async" [value]="test.id">{{test.description}}</option>
   </select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM