Issue
In the given code snippet, there is an observable operation to fetch products asynchronously. When assigning the result to an additional variable (productList
) before assigning it to the main variable (productDetailTable
), the dropdown momentarily shows undefined
. However, after clicking multiple times, the options are eventually displayed. On the other hand, directly assigning the result to the main variable (productDetailTable
) instantly populates the dropdown.
Code that momentarily shows undefined
:
this.productList = await this.ProductService.getProductsById(projectId).toPromise();
this.productDetailTable = this.productList;
Code that instantly populates the dropdown:
this.productDetailTable = await this.ProductService.getProductsById(projectId).toPromise();
Dropdown in the template:
<ng-multiselect-dropdown
[placeholder]="'aaaaaaaaaa'"
formControlName="aaaaaaaaaa"
[settings]="dropdownSettings"
[data]="productDetailTable"
class="singleselect"
[(ngModel)]="aaaaaaaaaaaaa"
[ngModelOptions]="{standalone: true}">
</ng-multiselect-dropdown>
Solution
Definition from mozilla:
Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected.
your code:
this.productList = await this.ProductService.getProductsById(projectId).toPromise();
This piece of code will return a promise-returning
function that will be resolved when the api call comes back, then move on to evaluate the next expression. which is
this.productDetailTable = this.productList;
By the time the above expression is evaluated, the promise is still pending (and this.productList
is still undefined). That's why the variable productDetailTable
is undefined
initially.
In your other code, the variable productDetailTable
is defined to wait for the api call, so a value won't be assigned until the api comes back.
Answered By - Wen W
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.