![](/img/trans.png)
[英]Angular 9 mat-autocomplete not working properly with switchmap operator
[英]Mat-autocomplete is not working in ngOnInit(), Map() is not working
HTML-我正在尝试使用 Mat-autocomplete,但它在第一次加载组件时无法正常工作,即在 ngOnInit() 中,它说无法读取 null 的属性(读取“地图”)
<mat-form-field appearance="outline">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [(ngModel)]="element.NEW_AMENITY_NAME" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" class="assignedSeat-select" (optionSelected)='onSelect($event.option, i)'>
<mat-option *ngFor="let item of filteredOptions | async" [value]="item">
{{item}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
TS 文件 -
ngOnInit(): void {
this.infoService.AmenityList.subscribe((res)=>{
this.AmenityList = res;
this.assignForm.push(this.createForm(1))
this.dataSource = [...this.assignForm.controls];
console.log(this.dataSource.END_TIME , "data");
})
this.displayName = this.AmenityList.map(a=>a.DISPLAY_NAME);
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
同步/异步问题。
我建议您在进一步了解 JS 中的异步性之前了解什么是异步性。
但快速解决。
private _data$ = this.infoService.AmenityList.pipe(shareReplay(1));
public names$ = this._data$.pipe(
map(list => list.map(item => item.name))
);
ngOnInit(): void {
this._data$.pipe(first()).subscribe((res)=>{
this.assignForm.push(this.createForm(1))
this.dataSource = [...this.assignForm.controls];
console.log(this.dataSource.END_TIME , "data");
})
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
this.AmenityList
尚未设置,因此它的 null,理解响应仅来自订阅内部,外部的任何内容在结果到来之前运行。
ngOnInit(): void {
this.infoService.AmenityList.subscribe((res)=>{
// runs after response comes
this.AmenityList = res;
this.assignForm.push(this.createForm(1))
this.dataSource = [...this.assignForm.controls];
console.log(this.dataSource.END_TIME , "data");
// }) you ended it here so the below code runs before the response comes
this.displayName = this.AmenityList.map(a=>a.DISPLAY_NAME);
}); // move it here, any code that depends on the response should be called after response
data.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.