【问题标题】:Understanding HTTP in Angular 2 tutorial在 Angular 2 教程中理解 HTTP
【发布时间】: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

标签: http angular


【解决方案1】:

“app/heroes”网址并非指路由模块“heroes”。它指的是 in-memory-data-service.ts 中的英雄数据对象。所以这不是魔术。 URL 只是指数据对象,而不是路径。

https://angular.io/tutorial/toh-pt6 的文档过于简洁,无法清晰说明,我在 https://github.com/angular/angular.io/issues/3559 提出了需要改进的建议

【讨论】:

    【解决方案2】:

    这绝对不是魔法。

    发生的事情是您正在调用内存中 api 的 get 请求!

    看看in-memory-api

    基本上,InMemoryDataService 类从 InMemoryDbService 扩展而来,后者在内存中创建可观察的 api。

    把它想象成一个动态创建的存根,然后当你调用 get 方法时,调用将被重定向到那个包(通过 xhrbackend),然后你得到那个英雄列表。 .

    【讨论】:

    • 啊,我想我现在明白了。谢谢@xe4me。
    猜你喜欢
    • 2016-06-24
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 2016-10-25
    • 2017-03-06
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多