我正在关注Angular教程到第7步here
我的HeroService
在致电getHeroes()
时没有回复任何英雄。但我认为它应该返回in-memory-data.service.ts
中定义的模拟数据。该怎么纠正呢?
我没有找到解决方案,
heroesUrl
更改为app/heroes
angular-in-memory-web-api
重新安装npm install angular-in-memory-web-api --save
(当前安装的版本"angular-in-memory-web-api": "^0.5.0"
)我的代码如下:
的 app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { HeroDetailComponent} from './hero-detail.component';
import { HeroesComponent } from './heroes.component';
import { DashboardComponent } from './dashboard.component';
import { HeroService } from './hero.service';
@NgModule({
declarations: [
AppComponent,
HeroDetailComponent,
HeroesComponent,
DashboardComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule
],
providers: [HeroService],
bootstrap: [AppComponent]
})
export class AppModule { }
in-memory-data.service.ts
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{ id: 0, name: 'Zero' },
{ id: 11, name: 'Mr. Nice' },
{ 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' }
];
return {heroes};
}
}
hero.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Hero } from './hero';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HeroService {
private heroesUrl = 'api/heroes';
constructor(private http: Http) {}
getHeroes(): Promise<Hero[]> {
console.log('in getheroes');
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
getHero(id: number): Promise<Hero> {
return this.getHeroes().then(heroes => heroes.find(hero => hero.id === id));
}
}
更新:
问题由@federico scamuzzi在评论中解决
将.then(response => response.json().data as Hero[])
更改为.then(response => response.json() as Hero[])
修复它。
答案 0 :(得分:0)
don't use .data
? ..例如:
.then(response => response.json() as Hero[])
P.S - &gt;小心你正在使用哪个版本的Angular?在最新版本中,http提供程序在Httpclient中被更改