【问题标题】:Unable to populate json to FormArray. TypeError: data.map is not a function无法将 json 填充到 FormArray。类型错误:data.map 不是函数
【发布时间】:2021-08-08 13:06:38
【问题描述】:

我从 api 接收到这个 json 格式,需要将它填充到 FormArray 中。但我得到 TypeError: data.map is not a function。下面是代码sn-p。

{
    "data": [ 
        {
            "id": "ASR4324368",
            "name": "TTTTT",
            "amount": 100
        },
        {
            "id": "GTH435435435",
            "name": "AAAAA",
            "amount": 500
        }
    ]   
}


getProductJson() {
    this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
        .subscribe(
            (data: any[]) => {
                this.productForm = this.fb.group({
                    product: this.fb.array(
                        data.map(datum => this.generateDatumFormGroup(datum))
                    )
                });
            },
            error => {
                console.log(error);
            }
    );
}

private generateDatumFormGroup(datum) {
    return this.fb.group({
        id: this.fb.control({ value: datum.id, disabled: false }),
        productName: this.fb.control({ value: datum.name, disabled: false }),
        productAmt: this.fb.control({ value: datum.amount, disabled: false }),
    });
}

【问题讨论】:

  • 也许您的订阅会返回属性名称为“数据”且类型为“数组”的对象。在这种情况下,请尝试(res:any)=> { let MyArray:any[] = res.data; }

标签: json angular api


【解决方案1】:

你确定你得到数据吗?检查使用管道(点击)

 this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
    .pipe(tap(res=>{console.log(res)})) //<--add this line
    .subscribe(....rest-of your code...)

注意:我觉得你的要求很奇怪(但我真的不知道是否可以)我通常使用一些类似

this.httpClient.get('http://myapi/api/controller/action', { withCredentials: true })

【讨论】:

    【解决方案2】:

    已修改为以下内容并且可以正常工作。

    getProductJson() {
        this.httpClient.request('GET', 'getProductJSON', { withCredentials: true })
            .subscribe(
                (data: any[]) => {
                    this.raw = data;
                    this.productObj = this.raw.data;
    
                    this.productForm = this.fb.group({
                        product: this.fb.array(
                            this.productObj.map(datum => this.generateDatumFormGroup(datum))
                        )
                    });
                },
                error => {
                    console.log(error);
                }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多