[英]Mat-autocomplete is not working in ngOnInit(), Map() is not working
HTML- I'm trying to use Mat-autocomplete but its not working on very first time when component gets loaded ie in ngOnInit(), Its saying cannot read properties of null (reading 'map') 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 file - 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 || '')),
);
}
its not working on very first time when we are laoding the component, attached image of error-当我们加载组件时,它第一次无法正常工作,附上错误图像-
Sync/Async issue.同步/异步问题。
I suggest you learn what is asynchronicity in JS before going further.我建议您在进一步了解 JS 中的异步性之前了解什么是异步性。
But quick solution.但快速解决。
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
is not set yet so its null, understand response only comes inside subscribe, anything outside runs before the result comes. 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.