我必须用API的响应填充下拉列表。问题是api需要几个查询参数X
和Y
,这些参数基于屏幕中可以更改的不同字段,因此我不能在ngOnInIt()中调用getCategoryByXandY
api一次。
目前我有它的工作,但当我选择下拉菜单时,fetchCategories
函数被一次又一次地调用,导致API被垃圾邮件。我在不同的地方读到,这是造成大的性能问题,但我不能弄清楚如何做到这一点与纯管道。有人能告诉我这是对的方向吗?为什么呢?
服务:
@Injectable()
export class CategoryRestService {
private walletsUrl = 'api/items';
constructor(
private http: HttpClient
) {}
...
getCategoryByXandY(X: string, Y: string): Observable<CategoryDto[]> {
const url = `${this.itemUrl}/category/?param1=${X}¶m2=${Y}`;
return this.http.get<CategoryDto[]>(url);
}
}
HTML
...
<mat-form-field fxFlex.gt-sm="31%" *ngIf="isRequired()">
<mat-label>
Category
</mat-label>
<mat-select
formControlName="category"
[required]="isRequired()">
<mat-option
*ngFor="let c of fetchCategories()"
[value]="c.id">
{{c.name}}
</mat-option>
</mat-select>
</mat-form-field>
组件
{
categories: CategoryDto[]
constructor(
categoryService: CategoryRestService
){ }
...
fetchCategories() {
const X = this.getControl('x').value;
const Y = this.getControl('y').value;
this.categoryService.getCategoryByXandY(x, y).subscribe(
categories => {
categories.filter(category => category.status === 'ACTIVE');
this.categories = categories;
}
);
return this.categories;
}
}
除了David的建议,我在x
和y
的表单字段上设置了一个.valueChange
来触发API并更新categories
将fetchCategories()的let c改为let c。将它指向数据集,而不是函数。
HTML
<mat-form-field fxFlex.gt-sm="31%" *ngIf="isRequired()">
<mat-label>
Category
</mat-label>
<mat-select
formControlName="category"
[required]="isRequired()"
>
<mat-option
*ngFor="let c of categories"
[value]="c.id"
(click)="selected(c)"
>
{{c.name}}
</mat-option>
</mat-select>
</mat-form-field>
组件
在构造函数或ngOnInit()中添加
this.fetchCategories ()
在控制器
selected(value:any){
console.log('selected value',value);
}