简体   繁体   English

无法在Angular 2项目中检索JSON文件

[英]Unable to retrieve JSON file in Angular 2 project

I am trying to display static JSON data in my angular 2 project. 我正在尝试在我的angular 2项目中显示静态JSON数据。 I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages. 我收到控制台错误“ GET http:// localhost:4200 / app / data / MOCK_DATA.json 404(未找到)”,我已经添加了services.ts和component.ts页面。

service.ts 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 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)
  }

Since it is static. 由于它是静态的。 there is no need to http.get . 无需http.get

Create a json.ts file 创建一个json.ts文件

export your JSON file as 将您的JSON文件导出为

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

then import it where required 然后在需要的地方导入

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

then console.log(json) inside the class to check the file/json. 然后在类内部的console.log(json)来检查文件/ json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM