简体   繁体   中英

Bind data from API to Dropdown in Angular 7

I'm trying to populate a dropdown from a get API. I've created a service and using the observables returning the data to the component, which then subscribes to the service. I'm able to console.log the whole data (which is in a JSON array) but I'm not able to see any data in the dropdown.

I guess the problem is that view is getting rendered before the API data. I know there is a resolve method but what else I can try?

My question and code are very much similar to the below question and there are few things which I've already correct in my code like 'Project' is an array but the solution isn't working for me. There is no error in my code also:

Drop down does not populate with API data in Angular

Please find my code below: 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>

Note : I just figured out that problem seems to be with the " selectpicker " dropdown which is a third party plugin. Could you please suggest what I can do to resolve it?

You could try using the async pipe.

@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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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