Given the following code (test code), what is the best way to have only one call to the requested file? Currently, each time the button is pressed, a XHR request is done.
import {Injectable} from 'angular2/core';
import {Http} from 'angular2/http';
@Injectable()
export class MyService {
constructor(private http: Http) {}
getList() {
return this.http.get('./public/data.json')
.map(res => res.json());
}
getOne(id: number) {
return this.getList()
.map(data => data.filter(my => my.id === id)[0]);
}
}
Here's the json data file
[
{"id": 1, "name": "Data 1"},
{"id": 2, "name": "Data 2"},
...
]
Here is the component file. It uses a simple model file (which is only a class with id and name properties)
import {Component} from 'angular2/core';
import {MyService} from 'my-service';
import {MyModel} from 'my-model';
@Component({
selector: 'test',
templateUrl: `
<button (click)="getRandom()">Test</button>
<p>{{ selected.name }} ({{ selected.id }})</p>
`
})
export class MyComponent {
selected: MyModel;
constructor(private myService: MyService) {}
getRandom() {
let id = Math.floor((Math.random() * 10) + 1);
this.myService.getOne(id)
.subscribe((data: MyModel) => this.selected = data);
}
}
I'm not putting here all the stuff to bootstrap the application. But this shows the idea.
Many thanks