简体   繁体   English

如何将此JSON数据加载到Angular2中

[英]How to load this JSON data into Angular2

Im new to Angular2, I want to load this Json data and display in a page, Im not sure how to do..? 我是Angular2的新手,我想加载这个Json数据并在页面中显示,我不知道该怎么办..? From all sources I learnt I made a code and attached it below, But its not running because of some errors, can anyone help in fixing or writing a new code for me so that i can learn from it.. 从所有来源我了解到我制作了一个代码并将其附加到下面,但由于某些错误它没有运行,任何人都可以帮我修复或为我编写新代码,以便我可以从中学习。

Thanks in advance for the help. 先谢谢您的帮助。

My code file - student.json 我的代码文件 - student.json

[ { "name": "John", "id_number": "12", "attendance": "276 days", "grade": "A" }, ], this is my students.service.ts code [ { "name": "John", "id_number": "12", "attendance": "276 days", "grade": "A" }, ],这是我的students.service.ts代码

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



    @Injectable()
    export class StudentsService {

    constructor(private http:Http)
    { 
     }

    getStudents() {

    return this.http.get('./students.json')
    .map((response: Response) => {
        console.log("mock data" + response.json());
        return response.json();


    }

    }

and, this is my students.component.ts file 而且,这是我的students.component.ts文件

    import {Component} from '@angular/core';
    import { Http, Response } from '@angular/http';
    import {StudentsService} from './students.service'; 
    import 'rxjs/add/operator/map'
    import 'rxjs/Rx';

    @Component({
    selector: 'students',
    templateUrl: 'students.html',
    styleUrls: ['./students.scss']
     }) 
     export class students    {

       public students;

        constructor( private _studentsService:StudentsService, private     http:Http)
        {
          this.students = this._studentsService.getStudents();
            }
        ngOnInit() {
         this._load();
         }

         private _load() {
         this.students = this._studentsService.getStudents();

         }

         }

You can write a service to load your html from json file and available all over your application like below. 您可以编写一个服务来从json文件加载您的html,并在您的应用程序中提供,如下所示。

@Injectable()
export class ConfigService {
  public config: any;
  private configObs: Observable<any>;

  constructor(private http: Http) {
   }

  public load(filename: string): Observable<any> {
    if ( this.config ) {
      return Observable.of(this.config);
    } else {
      this.configObs = this.http.get(filename).map((res) => {
        this.config = this.config || res.json() || {};
        return this.config;
      });
    }

    return this.configObs;
  }
}

You can also put your data in typescript class format if that option is available referance answer 你也可以把你的数据在打字稿类格式,如果该选项可用全球化志愿服务青年答案

If you have JSON data and you want to show it in page. 如果您有JSON数据,并且想要在页面中显示它。

Use Data Table to show It. 使用数据表来显示它。

Here is the example you can see how to show on page. 以下是您可以看到如何在页面上显示的示例。 Please click Here 请点击这里

Assign our json to a varible 将我们的json分配给变量

 myData = [{
             "name": "John",
             "id_number": "12",
             "attendance": "276 days",
             "grade": "A"
          },
          ...
          ...
         ],

In your Html 在你的Html中

<ul>
     <li *ngFor="let data of myData">
         <div>{{data.name}}</div>
         <div>{{data.id_number}}</div>
         <div>{{data.attendance}}</div>
         <div>{{data.grade}}</div>
     </li>
</ul>

Hope it helps 希望能帮助到你

What you are dealing with is an Observable students , either you need to manually subscribe to that observable, or use the async pipe in the template which handles the subscribing for your. 您正在处理的是一个Observable students ,要么您需要手动subscribe该observable,要么使用模板中的异步管道来处理您的订阅。

Also you are now performing the request twice, in the constructor and in your OnInit . 此外,您现在正在构造函数和OnInit执行两次请求。 Remove one of those, I'd remove the one in the constructor, since I like to keep everything away from the constructor, that does not need to be there, like mentioned here: https://stackoverflow.com/a/35763811/6294072 删除其中一个,我将删除构造函数中的那个,因为我喜欢保持一切远离构造函数,这不需要在那里,如下所述: https//stackoverflow.com/a/35763811/ 6294072

Back to the subscribing... either do: 回到订阅...要么:

this.students = this._studentsService.getStudents();
<div *ngFor="let student of students | async">
  <p>{{student.name}}</p>
  <!-- ... -->
</div>

or: 要么:

this._studentsService.getStudents()
  .subscribe(students => {
     this.students = students;
  })
  <div *ngFor="let student of students">
    <p>{{student.name}}</p>
    <!-- ... -->
  </div>

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

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