1
我正在努力做一个带有角度2的http获取请求。我用Json信息创建了一个文件,我想用我的TeacherInfo类“获取”并使用它显示信息由在路由中使用的帐户组件来执行。 如果我在routerLink单击此元素没有任何显示,如果我切换到另一个routerLink既不存在(有前,所有routerLinks工作就好了)Angular 2 Http的问题GET
文件: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"
}
我使用节点和npm的最新版本,我没有得到编译错误,只是在浏览器控制台(其他SPA的部件没有准备好喷气机)中无关的错误。可观察到的实现在那里,因为起初我试图这样做,并得出结论,首先使用承诺更容易。
当我需要在地图中使用返回Observable? – OPV