【发布时间】:2016-12-25 12:03:48
【问题描述】:
我正在努力使用 Angular 2 执行 http 获取请求。我已经制作了一个包含我想用我的 TeacherInfo 类“获取”的 JSON 信息的文件,并使用它来显示帐户组件的信息,该组件是在路由中使用。
如果我点击这个元素的 routerLink 什么都不会显示,如果我切换到另一个 routerLink 则两者都没有(之前有,所有 routerLinks 都可以正常工作)
文件:TeacherInfo.service.ts
import {Injectable, OnInit} from '@angular/core';
import { Http, Response , Headers} from '@angular/http';
import { account } from '../components/account.component';
import {Observable} from "rxjs";
@Injectable()
export class TeacherInfo {
constructor ( private http : Http) {}
private url = '../test.json';
getInfo(){
return this.http.get(this.url)
.toPromise()
.then(response => response.json().data as account );
}
}
文件:account.component.ts
import {Component, OnInit} from '@angular/core';
import { TeacherInfo } from '../services/TecherInfo.service';
@Component({
template:`
<h2>This is not ready jet!</h2>
<p>
Willkommen {{name}}! <br/>
E-mail: {{email}}<br/>
</p>
`
})
export class account implements OnInit{
public id : number;
public name : string;
public email: string;
private acc : account;
constructor(private accountinfoservice : TeacherInfo) {
}
getInfo() {
this.accountinfoservice.getInfo()
.then(( info : account ) => this.acc = info );
}
ngOnInit () {
this.getInfo();
if ( this.acc != null ) {
this.id = this.acc.id;
this.name = this.acc.name;
this.email = this.acc.email;
}else {
console.log("there is no data! ");
}
}
最后是 test.json:
{
"id" : "1",
"name": "testname",
"email": "testemail"
}
我正在使用最新版本的 node 和 npm,并且在浏览器控制台中没有编译错误和无关的错误(其他 SPA 的部分尚未准备好)。存在可观察的实现是因为起初我尝试这样做,并得出结论,一开始使用 Promise 更容易。
【问题讨论】:
标签: json http angular typescript get