angular 教程无法从 http 调用接收数据
angular tutorial could not receive data from http call
我正在尝试按照教程步骤 7 HTTP (https://angular.io/tutorial/toh-pt6) 学习 Angular 2。但是 hero.service.ts
中的函数 getHeroes()
仍然 return 没有。
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
模拟服务是从 InMemoryDbService
实现的。
有什么想法吗?
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
。
我正在尝试按照教程步骤 7 HTTP (https://angular.io/tutorial/toh-pt6) 学习 Angular 2。但是 hero.service.ts
中的函数 getHeroes()
仍然 return 没有。
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
模拟服务是从 InMemoryDbService
实现的。
有什么想法吗?
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
。