In a lot of tutorials, some data (e.g. list of todos) is stored in service. Is it good practice? I'm new in Angular 2 and I want to learn how code right.
Some code example:
@Injectable()
export class JsonRestService {
jsonObject = {};
jsonContent = {};
constructor(private http:Http) {
this.getXmlInJson()
.subscribe(
data => this.startGeneratingHtmlTemplateProcess(data),
error => console.log(error + " - Błąd pobrania jsona")
);
}
getXmlInJson() {
let url = "http://localhost:8080/xml";
return this.http.get(url);
}
public convertRestJsonToObject$() {
this.getXmlInJson()
.subscribe(
data => this.startGeneratingHtmlTemplateProcess(data.json),
error => console.log(error + " - Błąd pobrania jsona")
);
}
private startGeneratingHtmlTemplateProcess(data) {
this.jsonObject = JSON.parse(JSON.parse(JSON.stringify(data))._body);
this.jsonContent = JSON.parse(JSON.stringify(data._body));
console.log(this.jsonObject);
console.log("Json:");
console.log(this.jsonContent);
}
showObjectInConsole() {
console.log("Wyzwolone prze przycisk: ");
console.log(this.jsonObject);
}
}
While services are often used to retrieve/update data by interacting with a data source, they can be quite handy in storing data as well. For example, if you need to retrieve a large piece of data, you can cache it in the service:
@Injectable()
export class DataService{
mydata: Array<string>[];
constructor(private http:Http){}
loadData(): Observable<string[]> {
if (this.mydata){
return Observable.from(this.mydata); // return from cache
} else
{
return this.http.get("./assets/LargeDataSet.json")
.map(res => res.json())
.do(data => this.mydata = data);
}
}
}
In this example, the retrieval of a large data set will happen on the first call of loadData(), while the subsequent calls will return the data fast without making a time-consuming http.get(). Since a service can be a singleton, many components can take an advantage of using the data cached in the service. You can also store an app state inside a singleton service.
The good practice is to use services to provide datas. A service is a class with method that call the api (or whatever) to get (or post, or put or delete) the data and return the result to the component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With