【发布时间】: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 文件夹中。
-
路径可能有误,请尝试删除
app、this._http.get("data/MOCK_DATA.json")或尝试相对路径'如this._http.get("../../data/MOCK_DATA.json"),具体取决于您的文件夹结构
标签: javascript json angular angular2-services