簡體   English   中英

如何以及何時在 Angular 中正確綁定下拉列表?

[英]How and when to bind a dropdownlist properly in Angular?

我使用以下方法在 Angular 中綁定下拉列表,但我認為我做錯了,因為有時我沒有得到預期的行為:

演示服務.ts

getProducts(): Observable<ProductDto> { ... }

product.component.ts:

products: ProductDto[] = [];

ngOnInit(): void {
    this.bindProducts();
}

bindProducts() {
    this.demoService.getProducts()
    .subscribe((list: ProductDto) => {
        this.products = list;
    });
    //for testing purpose
    const check = this.products;
}

test() {
    this.bindProducts();
    //for testing purpose
    const test= this.products;
}

1.是列表變量定義products: ProductDto[] = []; 是正確的? 或者我應該為此使用一些 Observable 參數嗎?

2.我應該在ngAfterViewInit()而不是ngOnInit()中填充下拉列表嗎? 為了更快地加載 forms?

3.上面的代碼中,我使用了subscribe方法,但是在綁定list的時候,無法讓this.products填寫到上面的test()方法中。 我認為這很可能是 subscribe 方法,但我怎樣才能讓這個變量稍后被填充而不是 onInit()? 我應該使用toPromise還是其他什么? 什么是正確的方法?

沒有“正確”的方式,只有“更好”的方式、“推薦”的方式和“優惠”的方式。

以下是我將如何處理它

product.component.ts:


export ProductComponent {
  products$ = this.demoService.getProducts();
}

是的,我已經刪除了OnInit生命周期鈎子和所有其他代碼。 我什至沒有聲明products$的類型,因為typescript會推斷出這一點。

然后在我的組件中,我可以使用async pipe

<ng-container *ngIf='products$ | async as products'>
  <!-- My code here -->
</ng-container>

基本上,我們允許 angular 為我們完成訂閱和取消訂閱等繁重的工作。

你可以看看這個沙盒演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM