2
votes

I was trying to load dropdown list from http response using angular2 service.

Here is my service method :

categories: any;
    getCategories() {
        let subscription = this.httpclient
          .get(this.server_url)
          .subscribe((data) => {
            this.categories = data;
            console.log(this.categories);
          });
      }

Component TS

categoryID: number;
constructor(public categoryservice: CategoryService) { }

  ngOnInit() {
    this.categoryservice.getCategories();
  }

And component html code is :

<select data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
       <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
 </select>

But since the response in getCategories() method takes a while, dropdown list is empty. If the response comes fast list loads properly.

Can anyone please help me in this scenario when response takes time to fetch data from server? How I can load the list after reponse comes?

2

2 Answers

0
votes

you can wrap the select around another div or ng-container and then check if the data is present or not and then only show the select option .

Like

<ng-container *ngIf = "categoryservice?.categories">
<select data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
       <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
 </select>
</ng-container>
0
votes

You can render your dropdown after the response comes with a simple *ngIf on your select, while before you can render a loading:

<my-loading *ngIf="!loadComplete"></my-loading>

<select *ngIf="loadComplete" data-width="20%" class="selectpicker" [(ngModel)]="categoryID">
       <option *ngFor="let category of categoryservice.categories" value= {{category.categoryId}} >{{category.categoryName}}</option>
</select>

And in your TS you just set loadComplete to true after your call is complete

loadComplete: boolean = false;

getCategories() {
        let subscription = this.httpclient
          .get(this.server_url)
          .subscribe((data) => {
            this.categories = data;
            this.loadComplete = true;
        }, err => {
           this.loadComplete = true;
           alert("An error occurred");
        });
}

Since you can't speed up your call, this way you render a loading until the call is completed. Hope it helps