Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

javascript - angular *ngFor from json

I am new to angular. Let me first give an overview of what i am trying to achieve because this is a long code I am showing the relevant part.

I have a list display component.

And I have (lets say 2) components animals, zone.

Lets say :

zone has 2 columns zone name and zone code,

animals has 3 columns animal code, animal name, animal zone

and so on (lets say for 10 other components)

each component will generate JSON and send it to display list component.

display list will parse the JSON and display it with ngFor

in short :

  1. each component will make JSON and send it to service , which has behavior subject
  2. service has behavior subject, that will receive that JSON
  3. display component will get the latest json from service's behavior subject
  4. finally display component will parse json and will display them using ngfor

My generating and sending JSON to display list component is ok.

For example, I will show you the JSON of zone component that is send to display component.

enter image description here

I need your help to process the JSON so that I can display it using ngFor on display component html.

Code:

data.service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private messageSource = new BehaviorSubject(null);
  currentMessage = this.messageSource.asObservable();
  constructor() { }
  changeMessage(message: any) {
    console.log('changed');
    console.log(message);


    this.messageSource.next(message);
  }
}

for zone (zone.component.ts) : [car.component.ts is as same as zone.component.ts don't get confused]

import { Component, OnInit } from '@angular/core';
import { DataService } from "../../services/data.service";
import { Router } from '@angular/router';

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

  jsonData: any;
  data: any;

  constructor(private router: Router, private dataService: DataService) {
  }

  dd() {
    this.setData(this.jsonData);
  }

  ngOnInit(): void {
    this.setJsonData();
  }

  async getJsonData() {
    const myurl: string = "http://localhost:3000/zone/get/all";
    const response = await fetch(myurl, { headers: { 'Content-Type': 'application/json' } });
    return await response.json();
  }

  async setJsonData() {
    this.jsonData = await this.getJsonData();
  }

  setData(newJsonData: any) {
    this.data = Object.entries(newJsonData);
  }

  navigateToDisplayList(){
    this.router.navigateByUrl('display-list');
  }

  newMessage() {
    this.dataService.changeMessage(this.jsonData);
    // console.log(this.jsonData);
    // console.log(this.data);
    this.navigateToDisplayList();
  }
}

for display : display-list.component.ts :

import { Component, OnInit } from '@angular/core';
import { DataService } from "../../services/data.service";

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

  data: any;

  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.currentMessage.subscribe(message => this.data = message);
  }

  dd(){
    console.log(this.data);
    document.body.innerText = this.data.toString();
  }
}

A special note :

Please don't think I haven't researched it yet just because I am not posting the display-list.html

LOOK MY ALGORITHM IS SIMPLE :

  1. OUTER LOOP FOR EACH ROW
  2. INNER LOOP FOR EACH COLUMN THAT IS IT. I DON'T NEED ANYTHING ELSE IN HTML

I have tried this approach :

<tr *ngFor="let x of data">
        <td *ngFor="let y of x">
            {{y}}
        </td>
</tr>    

Each time I am getting error: ngFor is not a known property

(which is funny: If I just comment the ngfor error is gone

or

If I just ngfor on a static array like 1,2,3,4,5 no error there )

Some other time : data can not be iterated

(another funny thing: clearly my JSON can be iterated and no quotation or bracket is missing)

I simply don't get it why angular can't iterate this thing

JSON for zone list :

[
   {
      "zonecode":3,
      "zonename":"d"
   },
   {
      "zonecode":4,
      "zonename":"d"
   },
   {
      "zonecode":15,
      "zonename":"kk"
   }
]

Another very special note :

You don't need to post an answer or comment if you are suggesting capture the JSON in a variable then just loop on console.log(object.zonename) .

Because I have no control over JSON, I have lets say 30 other components where no zonename is there. I have to display in HTML directly from JSON

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

updating my answer based on comments....I understand that you want to access the key value pairs inside the object and this can be done as below

<tr *ngFor="let x of data">
        <td *ngFor="let y of x | keyvalue">
            {{y.key}}:{{y.value}}
        </td>
</tr>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...