2016-08-18 125 views
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的部件沒有準備好噴氣機)中無關的錯誤。可觀察到的實現在那裏,因爲起初我試圖這樣做,並得出結論,首先使用承諾更容易。

回答

3

我認購簡單的JSON得到

調用代碼

ngOnInit(): void { 
    this._officerService.getOfficers() 
    .subscribe(officers => this.officers = officers), 
    error => this.errorMessage = <any> error; 
} 

和服務代碼

import { Injectable } from 'angular2/core'; 
import { Http, Response } from 'angular2/http'; 
import { Observable } from 'rxjs/Observable'; 

import { Officer } from '../shared/officer'; 

@Injectable() 

export class OfficerService{ 

private _officerUrl = 'api/officers.json'; 

constructor(private _http: Http){ } 

getOfficers() : Observable<Officer[]>{ 
    return this._http.get(this._officerUrl) 
     .map((response: Response) => <Officer[]>response.json()) 
     .catch(this.handleError); 
} 

private handleError(error: Response){ 
    console.error(error); 
    return Observable.throw(error.json().error || 'Server error'); 
} 

}

即返回數據作爲數組並鑄造正確的類型,雖然你也可以使用任何並返回[0],如果你只是exp等一個。

希望有幫助

+0

當我需要在地圖中使用返回Observable? – OPV