英文:
Angular - Cannot read properties of undefined (reading 'find') in ng-select
问题
I will provide a translation of the code-related portion you mentioned:
我在我的Angular-15应用程序中有以下代码:
**component.ts:**
```typescript
import { CountryService } from 'src/app/features/admin/services/country.service';
export class CountryCreateComponent {
countriesDatas!: any[];
selectedCountryCode!: string;
selectedCountryName!: string;
showDiv: boolean = false;
constructor(
private fb: FormBuilder,
private toastr: ToastrService
) {
}
createCountry() {
this.createCountryForm = this.fb.group({
CountryCode: ['', [Validators.required]],
CountryName: ['', [Validators.required]],
});
}
constructor(
private fb: FormBuilder,
private countryService: CountryService,
private toastr: ToastrService,
private bsModalRef: BsModalRef,
private modalService: BsModalService
) {}
ngOnInit(): void {;
this.createCountry();
this.loadAllCountries();
}
loadAllCountries(){
this.countryService.getCountriesDropdown().subscribe({
next: (res: any) => {
this.countriesDatas = res.data;
this.isLoading = false;
}
})
}
onCountryChange() {
const selectedCountry = this.countriesDatas.find(
(country) => country.countryCode === this.selectedCountryCode
);
this.selectedCountryName = selectedCountry
? selectedCountry.countryName
: '';
}
}
在ng-select更改时,我想将选定的CountryCode和CountryName填充到文本输入字段中。
component.html
<div class="form-group">
<label for="Country">Country:</label>
<ng-select
[items]="countriesDatas"
[selectOnTab]="true"
[searchable]="true"
bindValue="CountryCode"
bindLabel="CountryName"
placeholder="Select Country"
[multiple]="false"
[clearable]="true"
[(ngModel)]="selectedCountryCode"
(ngModelChange)="onCountryChange()"
required
formControlName="CountryCode"
>
</ng-select>
</div>
</div>
<div id="divshow">
<div class="form-group">
<input
type="text"
class="form-control"
formControlName="CountryName"
id="CountryName"
[value]="selectedCountryName"
/>
</div>
</div>
当ng-select更改时,我希望将选定的CountryName加载到
但我收到了此错误:
Cannot read properties of undefined (reading 'find')
并且指向:const selectedCountry = this.countriesDatas.find(
我应该如何解决这个问题?
Please note that I've translated the code portion as you requested, but resolving the error would require examining the actual code in detail. The error you mentioned is related to the "find" method, which suggests that "countriesDatas" might not be defined or initialized properly. You may need to ensure that "countriesDatas" is populated correctly in the "loadAllCountries" function before using it in "onCountryChange."
<details>
<summary>英文:</summary>
I am having this code in my Angular-15 application:
**component.ts:**
import { CountryService } from 'src/app/features/admin/services/country.service';
export class CountryCreateComponent {
countriesDatas!: any[];
selectedCountryCode!: string;
selectedCountryName!: string;
showDiv: boolean = false;
constructor(
private fb: FormBuilder,
private toastr: ToastrService
) {
}
createCountry() {
this.createCountryForm = this.fb.group({
CountryCode: ['', [Validators.required]],
CountryName: ['', [Validators.required]],
});
}
constructor(
private fb: FormBuilder,
private countryService: CountryService,
private toastr: ToastrService,
private bsModalRef: BsModalRef,
private modalService: BsModalService
) {}
ngOnInit(): void {;
this.createCountry();
this.loadAllCountries();
}
this.loadAllCountries(){
this.countryService.getCountriesDropdown().subscribe({
next: (res: any) => {
this.countriesDatas = res.data;
this.isLoading = false;
}
})
}
onCountryChange() {
const selectedCountry = this.countriesDatas.find(
(country) => country.countryCode === this.selectedCountryCode
);
this.selectedCountryName = selectedCountry
? selectedCountry.countryName
: '';
}
}
I want to populate the text input fields with selected CountryCode and CountryName using ng-select dropdown.
**component.html**
<div class="form-group">
<label for="Country"
>Country:</label
>
<ng-select
[items]="countriesDatas"
[selectOnTab]="true"
[searchable]="true"
bindValue="CountryCode"
bindLabel="CountryName"
placeholder="Select Country"
[multiple]="false"
[clearable]="true"
[(ngModel)]="selectedCountryCode"
(ngModelChange)="onCountryChange()"
required
formControlName="CountryCode"
>
</ng-select>
</div>
</div>
<div id="divshow">
<div class="form-group">
<input
type="text"
class="form-control"
formControlName="CountryName"
id="CountryName"
[value]="selectedCountryName"
/>
</div>
</div>
When the ng-select is onChanged, I want to load the selected CountryName into the text input in <div id="divshow">
But I got this error:
Cannot read properties of undefined (reading 'find')
and it points at: const selectedCountry = this.countriesDatas.find(
How do I resolve this?
</details>
# 答案1
**得分**: 1
你可以稍微改变初始化你的应用程序的方式
countriesDatas: any[] = [];
selectedCountryCode: string = '';
selectedCountryName: string = '';
不要告诉 TypeScript 你的未定义值不能为 null 或 undefined,只需设置一个默认值。接下来,我会检查你的订阅中 res.data
是否也不是 undefined。由于你使用了 any 类型, TypeScript 无法帮助你捕获错误,所以我建议设置一个与响应匹配的接口。
<details>
<summary>英文:</summary>
you can just initialize your app a bit different
countriesDatas: any[] =[];
selectedCountryCode: string = '';
selectedCountryName: string = '';
instead of telling the typescript that you undefined values cannot be null or undefined with `!`, just set a default value. Next thing i would check if `res.data` is not undefined as well in you subscription. Since you use any types you will get no help from typescript to help you catch bugs, so i suggest setting up the an interface matching the response.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论