5
我试图让下面的http tutorial从Angular2文档从JSON文件数据:获取从JSON数据与Angular2无极
服务:
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
组件:
import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',
template: // some template,
styles: // some style,
providers: [HeroService]
})
export class AppComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
constructor(private heroService: HeroService) { }
getHeroes(): void {
this.heroService.getHeroes().then(heroes => {
this.heroes = heroes;
console.log('heroes', this.heroes);
});
}
ngOnInit(): void {
this.getHeroes();
}
}
型号:
export class Hero {
constructor(
public id: number,
public name: string,
public power: string,
public alterEgo?: string
) { }
}
我取代private heroesUrl = 'app/heroes';
与我的终点是一个JSON文件(private heroesUrl = 'app/mockups/heroes.json';
),即根据hero
模型中包含的数据。
但是,当我运行我的应用程序时,我得不到任何数据,并且有任何错误消息。 我的代码不正确吗?
你从哪里得不到数据?你可以在你希望得到'数据'(或者其他名字)的问题的代码中添加一个'console.log(data);'吗? –
我可以在哪里添加'console.log(data)'? – smartmouse
我不明白这个问题。你期望什么变量具有价值?要调试它,你可以添加一个'console.log(...)'行。这可以让你调查自己,并让我们看到你的期望。当我不知道你期望会发生什么时,我无法回答你的问题。 –