2017-06-06 28 views
0

我想在我的angular 2项目中显示静态JSON数据。我得到一个控制台错误'GET http://localhost:4200/app/data/MOCK_DATA.json 404(Not Found)'我已经添加了我的services.ts和component.ts页面。无法检索Angular 2项目中的JSON文件

service.ts

import { Injectable } from '@angular/core'; 
import { ConfigurationService } from '../../configuration.service'; 
import { Http, Response, RequestOptions, Headers } from '@angular/http'; 
import { Observable } from 'rxjs'; 
import { ListItem } from './list-item'; 


@Injectable() 
export class DataService { 

    constructor(
    private _http: Http, 
    private _configurationService: ConfigurationService 
) {} 

get() : Observable<ListItem[]> { 
     return this._http.get("app/data/MOCK_DATA.json") 
     .map((response: Response) => <ListItem[]> response.json()) 

    } 
} 

app.component.ts

import { Component, OnInit } from '@angular/core'; 
import { Router } from '@angular/router'; 
import { DataService } from '../data.service'; 
import { ListItem } from './list-item'; 
import { Subscription } from 'rxjs'; 


@Component({ 
    selector: 'app-component', 
    templateUrl: 'component.html', 
    styleUrls: ['component.css'] 
}) 
export class Component implements OnInit { 


    busy:Subscription; 
    datas: ListItem[] = []; 


    constructor(
    private _dataService: DataService, 
    private _confirmationService: ConfirmationService, 
    private _authService: AuthService, 
    private _router: Router, 
) { 


    } 

    ngOnInit(){ 

    } 
getdatas() { 
    this.busy = 
     this._dataService.get() 
     .subscribe(data => this.datas = data) 
    } 
+0

我将我重定向到另一页 – userlkjsflkdsvm

+0

如果您正在使用angular-cli,则需要将其添加到资产文件夹并对该文件夹执行http请求。 – echonax

+0

角度cli只允许资产文件夹中的json?...是的,我正在使用角度cli – userlkjsflkdsvm

回答

3

由于它是静态的。没有必要http.get

创建json.ts文件

出口的JSON文件

export const json={ 
    "key":"value" 
} 

然后将它导入在需要

import { json } from './json.ts'

然后console.log(json)里面的类来检查文件/ JSON。