【问题标题】:Unable to retrieve JSON file in Angular 2 project无法在 Angular 2 项目中检索 JSON 文件
【发布时间】:2017-06-06 05:03:19
【问题描述】:

我正在尝试在我的 Angular 2 项目中显示静态 JSON 数据。我收到控制台错误 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' 我已经添加了我的 services.ts 和 component.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

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

【问题讨论】:

  • 我将我重定向到另一个页面
  • 如果你使用 angular-cli,你需要把它添加到你的 assets 文件夹,然后向那个文件夹发出 http 请求。
  • angular cli 只允许资产文件夹中的 json?...是的,我正在使用 angular cli
  • @userlkjsflkdsvm 一旦进入 prod 环境,angular-cli 会将您的文件捆绑到 dist 文件夹中,这样您的路径就会发生变化。这就是为什么你应该把你的静态文件放到 assets 文件夹中。
  • 路径可能有误,请尝试删除appthis._http.get("data/MOCK_DATA.json") 或尝试相对路径'如this._http.get("../../data/MOCK_DATA.json"),具体取决于您的文件夹结构

标签: javascript json angular angular2-services


【解决方案1】:

因为它是静态的。不需要http.get

创建一个json.ts 文件

将您的 JSON 文件导出为

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

然后在需要的地方导入

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

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

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多