我正在努力用角度2做一个http获取请求。我已经创建了一个包含我想要的Json信息的文件" get"使用我的TeacherInfo类并使用它来显示路由中使用的帐户组件的信息。 如果我在routerLink中单击此元素,则不会显示任何内容,如果我切换到另一个routerLink,则两者都没有(之前有所有的routerLinks工作正常)
file: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 );
}
}
file: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的部件都没有准备就绪)。可观察的实现是存在的,因为起初我试图这样做,并得出结论,它最初使用一个承诺更容易。
答案 0 :(得分: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');
}
}
即将数据作为数组返回并将其转换为正确的类型,但您也可以使用any并返回[0],如果您只是期望的那样。
希望有所帮助