2016-08-18 129 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