简体   繁体   English

如何解析angular9中的嵌套对象数组

[英]how to parse an array of nested objects in angular9

so i have this json (as it looks its an array of nested objects)所以我有这个 json(因为它看起来是一个嵌套对象数组)

[
    {
        "_id": "5f71c793007e542360a883e4",
        "nom": "modified",
        "description": "modified",
        "cours": [{
            "_id": "5f71d4e3a20bd03e10b766ee",
            "title": "test",
            "description": "test"
        }]
    },
    {
        "_id": "5f71ec3f78f8553718854219",
        "nom": "second",
        "description": "tesst",
        "cours": [{
            "_id": "5f71ec3f78f855371885421a",
            "titre": "hhea",
            "description": "hhaasas"
        }]
    }
]

this is the api service which does consume the api and retrieve the results这是 api 服务,它确实使用 api 并检索结果

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({providedIn: 'root'})

export class ApiService {
    private SERVER_URL = "http://localhost:3000/api";

    constructor(private httpClient: HttpClient) {}

    public fetchData() {
        return this.httpClient.get(`${this.SERVER_URL}/modules`);

    }
}

and here i'm fetching the data and storing it in a array "modules[]"在这里我正在获取数据并将其存储在数组“modules[]”中

import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {module} from '../models/module';
import {Observable} from 'rxjs/Observable';
import {ApiService} from '../api.service';

@Component({
    selector: 'app-all-modules',
    templateUrl: './all-modules.component.html',
    styleUrls: ['./all-modules.component.css']
})
export class AllModulesComponent implements OnInit {
    modules = [];
    constructor(private apiService: ApiService) {}
    ngOnInit(): void {
        this.apiService.fetchData().subscribe((data: module[]) => {
            console.log(data);
            this.modules = data;
        })
    }
}

and this is my model这是我的模型

export interface module {

    id: string;
    nom: string;
    description: string;
    cours: [{
        titre: string;
        description: string;
    }]

}

i'm trying to get each element in the array on the modules array but i'm getting all the json in one element我试图在模块数组上获取数组中的每个元素,但我正在一个元素中获取所有 json

Please try this.请试试这个。 You have to iterate over the array so that you can push the element by itself and not the whole array.您必须遍历数组,以便可以单独推送元素而不是整个数组。

this.apiService.fetchData().subscribe((data: module[]) => {
  data.forEach((element) => {
    this.modules.push(element);
  });
});

or in an easier way, do like this :或者以更简单的方式,这样做:

this.apiService.fetchData().subscribe((data: module[]) => {
    Array.prototype.push.apply(this.modules, data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM