【发布时间】:2016-02-04 08:22:59
【问题描述】:
我正在尝试通过我的 Angular 服务读取 JSON 文件。 当我不使用该服务时,我可以轻松读取 JSON 数据并将其绑定到变量中。 但是当我使用服务来执行此操作时,它不起作用。 它显示以下错误:
Failed to load resource: the server responded with a status of 404.
我确定我写的路径是正确的。
下面是代码:
- app.component.ts
import {Component} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
import { DataService } from '../services/data.service';
@Component({
selector: 'my-app',
providers: [DataService],
templateUrl: 'app/app.component.html'
})
export class AppComponent {
public record;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getDetails()
.subscribe((customers:any[]) => {
this.record = customers;
});
}
}
- data.service.ts
import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class DataService {
constructor(private http: Http) { }
getDetails() {
return this.http.get('../uicomponent.json')
.map((res:Response) => res.json());
}
}
- 引导配置
<script>
System.config({
map: { 'rxjs': 'node_modules/rxjs' },
packages: {
app: { format: 'register', defaultExtension: 'js' },
'rxjs': {defaultExtension: 'js'}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
- main.ts
import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {AppComponent} from './app.component'
bootstrap(AppComponent, [
HTTP_PROVIDERS
]);
【问题讨论】:
-
我不确定我是否理解您的问题。您是否认为 Angular 没有找到该服务(如问题标题所示)或者该服务无法获取 json 文件?请求的 URL 是什么?实际应该是怎样的?
-
angular 2 无法找到服务..虽然我写的路径正确..因为我在其他项目中以同样的方式使用过服务,它们工作正常@GünterZöchbauer
-
您的路径似乎有效。您能否分享更多信息,例如 SystemJS 或 Webpack 配置,可能是您的存储库或 plunker...?
-
您能提供完整的错误信息吗?我的意思是哪个资源加载失败...谢谢!
-
我猜问题可能来自你的相对路径 (
'../uicomponent.json')...
标签: javascript angularjs json angular