简体   繁体   中英

Struggling to read in JSON file in Angular 2+ project

I have used the Angular CLI to set up this project so the standard folder layout holds. I am trying to practice reading in a JSON file from src/app/assets/items.json and use it to display these items in the html.

items.json:

{
   "results": [
      "Item 1",
      "Item 2",
    ]
}

app.service.ts in src/app/:

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class AppService {
    private greetUrl = 'api/Hello';

    // Resolve HTTP using the constructor
    constructor(private _http: Http) { }

    findJSON(): Observable<any> {
        return this._http.get('assets/items.json').map((response: Response) => {
            return response.json();
        });
    }

    sayHello(): Observable<any> {
        return this._http.get(this.greetUrl).map((response: Response) => {
            return response.text();
        });
    }
}

and app.component.ts in src/app:

import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';

import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  greetings = '';
  itemsjson : string;

  constructor(private _appService: AppService) { }

  ngOnInit(): void {
    this._appService.findJSON()
      .subscribe(
      result => {
        this.itemsjson = result;
      }
      );
  }
} 

and app.component.html in src/app/:

<html lang="en">
  <link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap.min.css">
  <head>
    <meta charset="utf-8">
    <title>Yik-Yak Clone</title>
  </head>
  <body>
    <div class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <a href="../" class="navbar-brand">Yik-Yak Clone</a>
        </div>
      </div>      
    </div>

      <!-- Containers
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div>

      <!-- Containers
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div>

          <!-- 
      ================================================== -->
      <div class = "container">
        <div class="row">
          <div class="col-lg-12">
            <div class="bs-component">
              <div class="jumbotron">
                <h1>{{itemsjson}}</h1>
              </div>
            </div>
          </div>
        </div> 
      </div> 


  <nav class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
      <div class="navbar-head">
        <div class = "col-sm-3"></div>
        <div class="col-sm-6">
          <div class="form-group">
            <input class="form-control input-lg" type="text" id="inputLarge">
          </div>
        </div>
        <div class = "navbar-brand">
          <div class="col-sm-2">
            <div class="form-group">
              <button type="submit" class="btn btn-primary">greetings</button>
            </div>
          </div>
        </div>
        <div class = "col-sm-1"></div>
      </div>
    </div>
  </nav>

  </body>
</html>

Every example online and similar question online seems to imply that this is all correct.

You want to be looping through your results property returned by your json.

<div class ="container" *ngFor="let item of itemsjson?.results">
    <div class="row">
        <div class="col-lg-12">
            <div class="bs-component">
                <div class="jumbotron">
                    <h1>{{item}}</h1>
                </div>
            </div>
        </div>
    </div> 
</div> 

We also are using the safe navigation operator (?) because itemsjson is not initially defined itemsjson?.results

There is nowhere you are using itemsjson in your HTML, probably you need

<div class="jumbotron">
    <h1>{{itemsjson | json }}</h1> 
</div>

First, check your itemsjson on console.log and just pass it in your template. If you want to read your data in loop use - *ngFor = 'let data of itemsjson;let i = index' and pass {{data}} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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