在 Angular 中填写下拉列表时的正确选项是什么?
What is the proper option when filling dropdownlist in Angular?
我正在填写一个列表并将其传递给另一个组件。该列表用作下拉列表的选项,我不确定填充此列表的正确方法是什么。这里是服务方法和相关方法:
service.ts
list(): Observable<CarDto> { }
parent.html
<child-component [cars]="cars" *ngIf="cars && cars.length > 0"> </child-component>
还是我应该使用 async
?
<child-component [cars]="cars$ | async" *ngIf="((cars$ | async) && (cars$ | async)?.length > 0"> </child-component
parent.ts
cars: any;
listCars() {
this.service.list().subscribe((list: CarDto) => {
this.cars= list.cars;
});
还是应该使用 async
?、Promise 等???
cars$: Observable<any>;
this.cars$ = this.service.list().pipe(shareReplay());
child.ts
@Input() cars: any;
这种情况的正确方法是什么?由于数据在生命周期内是不会改变的,所以唯一要注意的是快速加载父子组件没有任何问题。另一方面,请记住我的服务方式 returns Observable
.
从最佳实践的角度来看,异步管道是您应该更喜欢的方式。但是在同一个可观察对象上使用异步管道并不好。请考虑将您的模板包装在 ng-container
中,为您存储值。
<ng-container *ngIf="cars$ | async as cars">
<child-component [cars]="cars" *ngIf="cars && cars.length > 0"></child-component>
</ng-container>
我正在填写一个列表并将其传递给另一个组件。该列表用作下拉列表的选项,我不确定填充此列表的正确方法是什么。这里是服务方法和相关方法:
service.ts
list(): Observable<CarDto> { }
parent.html
<child-component [cars]="cars" *ngIf="cars && cars.length > 0"> </child-component>
还是我应该使用 async
?
<child-component [cars]="cars$ | async" *ngIf="((cars$ | async) && (cars$ | async)?.length > 0"> </child-component
parent.ts
cars: any;
listCars() {
this.service.list().subscribe((list: CarDto) => {
this.cars= list.cars;
});
还是应该使用 async
?、Promise 等???
cars$: Observable<any>;
this.cars$ = this.service.list().pipe(shareReplay());
child.ts
@Input() cars: any;
这种情况的正确方法是什么?由于数据在生命周期内是不会改变的,所以唯一要注意的是快速加载父子组件没有任何问题。另一方面,请记住我的服务方式 returns Observable
.
从最佳实践的角度来看,异步管道是您应该更喜欢的方式。但是在同一个可观察对象上使用异步管道并不好。请考虑将您的模板包装在 ng-container
中,为您存储值。
<ng-container *ngIf="cars$ | async as cars">
<child-component [cars]="cars" *ngIf="cars && cars.length > 0"></child-component>
</ng-container>