【发布时间】:2017-10-16 08:10:03
【问题描述】:
最近我在学习angular2的http客户端,我已经用angular-in-memory-web-api完成了demo。现在我想用http.get来请求本地json数据,但是浏览器告诉我zone.js:1980 GET http://localhost:4200/app/hero.json 404 (Not Found),阅读相关帖子后Angular2 404 Not Found for URL: http://localhost/WebApi2/api/hero 和the simliar one of angular get 中的'angular-in-memory-web-api' ,InMemoryWebApiModule.forRoot(HeroData) 和我的项目中的相关文件,但404 (Not Found) 的问题仍然存在,关键代码如下:
//app.module.ts
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
],
declarations: [
AppComponent,
HeroListComponent,
HeroListPromiseComponent,
WikiComponent,
WikiSmartComponent
],
providers: [ requestOptionsProvider ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
//hero.service.tsenter code here
@Injectable()
export class HeroService {
private heroesUrl = 'app/hero.json';
constructor (private http: Http) {}
getHeroes(): Observable<Hero[]> {
// debugger;
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
// http.get or http.post return the json obj
let body = res.json();
return body.data || { };
}
如果您想要所有代码,我已将其推送到我的 github。这是address
谁能帮帮我
【问题讨论】:
-
我认为您只需将您的网址设置为
private heroesUrl = './app/hero.json'; -
你还没有订阅 http.get 方法返回的 observable。
-
@Mike Tung 我尝试使用
private heroesUrl = './app/hero.json';代替private heroesUrl = './app/hero.json';,但这没用, -
@Yashwardhan Pauranik hero.service 只负责从服务器获取数据,它的方法会将 Observable 对象返回给组件,然后订阅 Observable。如果你有兴趣,你愿意克隆我的完整代码表单my github 并改进它?
标签: javascript angularjs json