【问题标题】:angular tutorial could not receive data from http call角度教程无法从 http 调用接收数据
【发布时间】:2017-10-21 16:10:59
【问题描述】:

我正在尝试按照教程步骤 7 HTTP (https://angular.io/tutorial/toh-pt6) 学习 Angular 2。但是 hero.service.ts 中的函数 getHeroes() 仍然没有返回任何内容。

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
    .toPromise()
    .then(response => response.json().data as Hero[])
    .catch(this.handleError);
} 

模拟服务是从InMemoryDbService 实现的。

有什么想法吗?

【问题讨论】:

    标签: angular angular2-services


    【解决方案1】:

    HTTP 客户端将从内存中的 Web API InMemoryDbService 获取并保存数据。基本上,这意味着InMemoryDbService 将模拟您的服务器,该服务器将接收 HTTP 请求并做出响应。

    您是否安装了模块in-memory-web-api?如果没有,你可以安装它:npm install --save angular-in-memory-web-api

    不要忘记在你的 app.module 中导入模块(这个导入应该只在 HttpModule 的导入之后进行):

    imports: [
        ...
        HttpModule,
        InMemoryWebApiModule.forRoot(InMemoryDataService),
        ...
      ],
    

    此外,in-memory-web-api 的新 api 中引入的新更改不再将 HTTP 响应包装在 data 属性 (github) 中。所以应该是response.json() 而不是response.json().data

    【讨论】:

    • 您是否将模块添加到app.module.ts 中的导入依赖项中?
    • 我确实添加了 InMemoryWebApiModule.forRoot(InMemoryDataService),
    • 您的hero.service.ts 的其他功能是否有效,还是只有getHeroes 无效?
    • 如果使用response.json()而不是response.json().data,它可以工作
    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 2017-12-21
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2021-06-24
    相关资源
    最近更新 更多