简体   繁体   中英

Unable to retrieve JSON file in Angular 2 project

I am trying to display static JSON data in my angular 2 project. 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.

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)
  }

Since it is static. there is no need to http.get .

Create a json.ts file

export your JSON file as

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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