无法从JSON获取某些数据,返回未定义的Angular 6

时间:2018-07-06 14:44:27

标签: json angular typescript observable

我正在尝试从此JSON中提取“数据”,但结果始终未定义。

提取出现此错误的代码:

ngOnInit(): void {
    this.testService.getTestWithObservable().subscribe(
        res => {
            let user = res["users"];
            let user_data = user["data"];

            this.user_data = user_data;

            console.log(user_data);
            console.log(res);
        }
    );
}

res输出整个JSON,但user_data抛出:

错误TypeError:无法读取未定义的属性“数据”     在SafeSubscriber._next

JSON

[{
    "id": 1,
    "users": {
        "user_id": 14,
        "data": [{
            "name": "James",
            "age": 20
        },
        {
            "name": "Damien",
            "age": 25
        }]
    }
}
{
    "id": 2,
    "users": {
        "user_id": 11,
        "data": [{
            "name": "James",
            "age": 20
        },
        {
            "name": "Damien",
            "age": 25
        }]
    }
}]

2 个答案:

答案 0 :(得分:1)

您的JSON是一个数组,因此您需要使用索引或循环来访问您的项之一,如下所示:

ngOnInit(): void {
    this.testService.getTestWithObservable()
        .subscribe(
            res => res.forEach(user => this.user_data = [...(this.user_data || []), user['users']['data']]);
        );
}

或者:

ngOnInit(): void {
    this.testService.getTestWithObservable()
        .subscribe(
            res => this.user_data = res[0]['users']['data']);
        );
}

第一个代码将每个用户的所有user_data属性存储在data数组中

答案 1 :(得分:0)

结果是数组,因此您必须使用索引来访问数组数据,

ReadWriteOnce

通过ngFor循环抛出数据

    this.testService.getTestWithObservable()
     .map( result => result.map( i => i.users.data) )  // array of data array
     .subscribe(
        res => {

            this.user_data = [];
            res.forEach(i => this.user_data(...i));
            console.log(this.user_data); // all users data as array 
        }
    );
}