大佬教程收集整理的这篇文章主要介绍了AngularJS 2:从json文件获取数据不起作用,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
找到了 !这是由于InMemoryBACkendservice
,并InMemoryDataservice
在使用
文件,这似乎是“重定向”从http.get调用方法。注释main.ts文件中的这些行可解决此问题:
// imports for loading & configuring the in-memory web API
import { XHRBACkend } from '@angular/http';
//import { InMemoryBACkendservice, SEED_DATA } from 'angular2-in-memory-web-API';
//import { InMemoryDataservice } from './in-memory-data.service';
// The usual bootstrapPing imports
import { bootstrap } from '@angular/platform-browser-dynamic';
import { http_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
import { appRouterProvIDers } from './app.routes';
bootstrap(AppComponent, [
appRouterProvIDers,
http_PROVIDERS
/*,
{ provIDe: XHRBACkend, useClass: InMemoryBACkendservice }, // in-mem server
{ provIDe: SEED_DATA, useClass: InMemoryDataservice } // in-mem server data
*/
]);
我正在尝试从Angular服务hero.service.ts获取json数据。当在MemoryDataservice中使用伪造的http
API时,一切正常,我从in-memory-
data.service.ts文件中获取json数据。但是,当我尝试从真实的json文件中获取数据时,它不起作用,并且在浏览器中出现错误“找不到集合”。
以下是文件内容(所有3个文件都位于app /文件夹中):
hero.service.ts:
import { Injectable } from '@angular/core';
import { Headers,http,ResponsE} from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './hero';
@Injectable()
export class Heroservice {
private heroesUrl = 'app/fakeListOfHeroes'; // URL to web api
//private heroesUrl = 'app/heroes.json'; // URL to JSON file
constructor(private http: http) { }
getHeroes(): Promise<Hero[]>
{
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
private handleError(error: any)
{
console.error('An error occurred',error);
return Promise.reject(error.message || error);
}
}
hero.service.ts:
export class InMemoryDataservice {
createdb() {
let fakeListOfHeroes = [
{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 {fakeListOfHeroes};
}
}
heroes.json:
{
"data": [{
"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"
}]
}
浏览器错误:
浏览器错误
任何帮助,将不胜感激。谢谢!
以上是大佬教程为你收集整理的AngularJS 2:从json文件获取数据不起作用全部内容,希望文章能够帮你解决AngularJS 2:从json文件获取数据不起作用所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。