【发布时间】:2017-08-25 03:41:55
【问题描述】:
我一直在学习 Angular 2 Tour of Heroes 教程,但我不理解 lesson on using HTTP 从服务中获取数据。
在英雄服务的本课中,变量heroesUrl 被声明为“app/heroes”。
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 { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
{ id: 11, name: 'Mr. Nice (api)' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' },
{ id: 21, name: 'Mister Man' }
];
return { heroes };
}
}
但在路由模块中,“heroes”(我假设它与“app/heroes”相同)指向 HeroesComponent。
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
在 HeroesComponent 中,getHeroes() 函数调用了this.heroService.getHeroes() 函数:
getHeroes(): void {
//Result of heroService.getHeroes is a Promise
this.heroService.getHeroes().then(heroesresult => this.heroes = heroesresult);
}
表面上看起来HeroesComponent.getHeroes() 调用HeroService.getHeroes() 然后将http.get 返回到 HeroesComponent,而不是数据源。
这一切都对我有用(就像魔术一样),但没有解释如何通过从 HeroesService 到 this.http.get(this.heroesUrl) 的调用获取内存数据服务中的数据。
有人可以帮我理解吗?
【问题讨论】:
-
private heroesUrl = 'app/heroes'; // URL to web api,这只是一个模拟url,当你开发自己的应用程序时,只需用你的url替换那个url