如何以及何时在 Angular 中正确绑定下拉列表?

How and when to bind a dropdownlist properly in Angular?

我在 Angular 中使用以下方法绑定下拉列表,但我认为我做错了什么,因为有时我没有得到预期的行为:

demoService.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() 中填充下拉列表吗?为了更快地加载表单?

3. 在上面的代码中,我使用了subscribe方法,但是在绑定列表时,我无法让this.products填充在test() 上面的方法。我认为这很可能是 subscribe 方法,但我怎样才能让这个变量稍后被填充而不是 onInit()?我应该使用 toPromise 还是其他什么?正确的方法是什么?

没有'proper'方式只有'better'方式'recommended'方式和'preferential'方式。

以下是我的处理方法

product.component.ts:


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

是的,我删除了 OnInit 生命周期挂钩和所有其他代码。我什至没有声明 products$ 的类型,因为 typescript 会推断出这一点。

然后在我的组件中我可以使用 async 管道

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

基本上,我们允许 angular 为我们完成繁重的工作,例如订阅和取消订阅。

你可以看看this sandbox demo