我正在尝试在我的 Angular 2 项目中显示静态 JSON 数据。我收到控制台错误“GET http://localhost:4200/app/data/MOCK_DATA.json” 404(未找到)'我已添加我的 services.ts 和 component.ts 页面。
服务.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)
}
最佳答案
因为它是静态的。无需http.get
。
创建一个json.ts
文件
将 JSON 文件导出为
export const json={
"key":"value"
}
然后在需要的地方导入
从 './json.ts' 导入 { json }
然后在类内console.log(json)
检查文件/json。
关于javascript - 无法在 Angular 2 项目中检索 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44381735/