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