0

I can't wrap my head around how I should loop through a nested JSON file I've got.

This is the code I've got si far:

JSON:

[
    {  
    "produkt": "dammsugare",
    "produktinformation": [
        {
        "artikelnr": 9121283726,
        "typ": "ean"
        },
        {
        "artikelnr": "dasu",
        "typ": "varukod"
        }
    ]
    },
    {
    "produkt": "hammare",
    "produktinformation": [
        {
        "artikelnr": 91246128736,
        "typ": "ean"
        },
        {
        "artikelnr": "traffaspik",
        "typ": "varukod"
        }
    ]
    }
]

Service.ts:

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

@Injectable({
  providedIn: 'root'
})
export class MyserviceService {

  constructor(private http:HttpClient) { }

  getProducts() {
    console.log('getProducts()');
    return this.http.get('/assets/produkter.json');
  }

  getInfo() {
    console.log('getInfo()');
    return this.http.get('/assets/produkter.json')
  }
}

Component.ts:

import { Component, OnInit } from '@angular/core';
import { MyserviceService } from '../myservice.service';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {

  arrProducts: any;

  constructor(private myserviceService: MyserviceService) { }

  ngOnInit() {
    this.myserviceService.getProducts().subscribe((data) => {
      console.log(data);
      this.arrProducts = data;
    });
  }
}

Component.html:

<p>list works!</p>
<ul *ngFor="let product of arrProducts">
    <li>{{ product.produkt }}</li>
    <li>{{ product.productinformation.artikelnr }}</li> <!-- THIS LINE IS WRONG, BUT I DON'T KNOW WHAT TO DO-->
</ul>

As you can see, I do not know how to edit the component.html for it to display the nested JSON file.

I hope there's someone who could help me out. Thanks! :)

1

2 Answers 2

1

you just nest ngFor...

<p>list works!</p>
<ul *ngFor="let product of arrProducts">
    <li>{{ product.produkt }}</li>
    <li *ngFor="let info of product.produktinformation">{{ info.artikelnr }}</li>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

0

Your JSON structure says productinformation.artikelnr, but you want to access produktinformation.artikelnr, i. e. you misspelled a c and wrote k instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.