角度 - 在数组中找不到值



大家好,我目前在使用find for array时遇到了问题。

代码:https://codeshare.io/EBoBEX

line 80上是我无法工作的代码。Line 69有类似的功能,但它有效。

错误信息:

ERROR TypeError: Cannot read property 'customer_fullname' of undefined

我基本上试图将值输入myForm。我正在使用mongodb,这就是文档中的内容:

1. _id:6114e3c1c5934f0fc8da2156

2. fullname:"John Pearson"

3. email:"john@gmail.com"

4. address:"Yishun street 69 Blk 420"

5. user_id:"61003363e8ded0257c63592a"

我使用user_id: this.authService.getUserID(),因为从我的认证服务中获得用户id后,我将其放入myForm作为user_id,然后我尝试使用它来查找客户的全名,因为user_id值与我的用户的_id相同。

当我做console.log(this.customers);它显示了以下内容:

[{…}] 0: address: "Yishun street 69 Blk 420" email: "john@gmail.com" fullname: "John Pearson" user_id: "61003363e8ded0257c63592a" _id: "6114e3c1c5934f0fc8da2156" [[Prototype]]: Object length: 1 [[Prototype]]: Array(0)

我要做的是从基于user_id的客户数组中找到,对不起,如果我不清楚

任何帮助将是感激的,提前感谢你这么多!

如果您使用ReactiveForms,请使用formControlName

<select id='name' name='name' formControlName="user_id"
(change)="selectChangeHandler($event)">

要给FormGroup中的formcontrol赋值,使用setValue给它赋值<罢工>

this.myForm.value.id = this.selectedId;
//really I don't know if is user_id or id
this.myForm.get('id').setValue(this.selectedId);

你总是可以得到一个属性你可以两步完成:

this.myForm.value.customer_fullname =
this.customers.find(x=>x.user_id===this.myForm.value.user_id)
.customer_fullname;
const customer=this.customers.find(x=>x.user_id===this.myForm.value.user_id)
this.myForm.get('customer').setValue(
customer?customer.customer_fullname:null)

如果所有值都与数组中的元素相关,则可以使用唯一字段,然后,在提交中可以简单地使用找到它的元素:"customer">

最新更新