我是Angular2的新手,我想加载这个Json数据并在页面中显示,我不知道该怎么办..?从所有来源我了解到我制作了一个代码并将其附加到下面,但由于某些错误它没有运行,任何人都可以帮我修复或为我编写新代码,以便我可以从中学习..
提前感谢您的帮助。
我的代码文件 - student.json
[
{
"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();
}
}
,这是我的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();
}
}
答案 0 :(得分:1)
您可以编写一个服务来从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;
}
}
如果该选项可用,您还可以将数据放入打字稿类格式referance answer
答案 1 :(得分:0)
答案 2 :(得分:0)
将我们的json分配给变量
// Example program
#include <iostream>
#include <string>
struct A;
typedef void (*cb)(A*);
struct A
{
int m_a;
static void foo(A* aref)
{
std::cout << "Print a: " << aref->m_a << "\n";
}
A(cb b=foo)
{
m_a = 100;
b(this);
}
};
int main()
{
A a;
}
在你的Html中
myData = [{
"name": "John",
"id_number": "12",
"attendance": "276 days",
"grade": "A"
},
...
...
],
希望有所帮助
答案 3 :(得分:0)
您正在处理的是Observable students
,您需要手动subscribe
到该可观察对象,或者在模板中使用异步管道来处理订阅。
此外,您现在正在构造函数和OnInit
中执行两次请求。删除其中一个,我删除了构造函数中的一个,因为我喜欢将所有内容远离构造函数,这不需要在那里,如下所述:https://stackoverflow.com/a/35763811/6294072
回到订阅...要么:
this.students = this._studentsService.getStudents();
<div *ngFor="let student of students | async">
<p>{{student.name}}</p>
<!-- ... -->
</div>
或:
this._studentsService.getStudents()
.subscribe(students => {
this.students = students;
})
<div *ngFor="let student of students">
<p>{{student.name}}</p>
<!-- ... -->
</div>