小编tka*_*rra的帖子

AngularJS 2:从json文件获取数据不起作用

我试图从Angular服务hero.service.ts获取json数据.当使用虚假的http API inMemoryDataService时,一切正常,我从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);
    } …
Run Code Online (Sandbox Code Playgroud)

json http angular

4
推荐指数
1
解决办法
5080
查看次数

标签 统计

angular ×1

http ×1

json ×1