Reputation: 13805
I am trying to read JSON file through my angular service. When I am not using the service I can easily read JSON data & bind it inside variable. But When I am using service to perform this,its not working. Its showing following error:
Failed to load resource: the server responded with a status of 404.
I am sure that I have written path correctly.
Below are is the code:
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;
});
}
}
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>
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
]);
Upvotes: 0
Views: 889
Reputation: 202256
The services
folder should be under the app
folder. According to your SystemJS configuration, only resources under this folder are loaded using this configuration:
System.config({
(...),
packages: {
app: { format: 'register', defaultExtension: 'js' },
(...)
}
});
format: 'register', defaultExtension: 'js'
This means that SystemJS will automatically try to load modules using the js
extension.
So the structure should be the following:
project
- app
- app.component.ts
- main.ts
- services
- data.service.ts
Within the app.component.ts
file, you can import the service using:
import {DataService} from './services/data.service';
According to its configuration, SystemJS will try to load the localhost:3000/app/services/data.service.js
that should be present if the TypeScript compiler did its job before ;-)
Thierry
Upvotes: 2