我正在尝试在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)
}
答案 0 :(得分:3)
因为它是静态的。没有必要http.get
。
创建json.ts
文件
将您的JSON文件导出为
export const json={
"key":"value"
}
然后在需要时导入
import { json } from './json.ts'
然后在类中console.log(json)
检查文件/ json。