I have created a simple injectable service in TypeScript for Angular 4. This service is designed to fetch a JSON file from the network and store the data as an array in its property called data
. Other classes can then access this data using the method getData()
.
The issue I am facing is that the assignment operation to update this.data
seems to be ignored. Even though I use this.data = data
, the value of this.data
does not change. Everything else in the code is functioning correctly.
Here is the code snippet for the service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class JsonFetcherService {
private data: any;
constructor(private http: HttpClient) {
this.data = null;
}
public fetch(url: string): void {
this.http.get(url).subscribe(this.setData);
}
private setData(data) {
this.data = data;
}
public getData(): any {
return this.data;
}
}
And here is a basic example class that utilizes this service:
import { Component } from '@angular/core';
import { JsonFetcherService } from '../jsonFetcherService/JsonFetcherService';
@Component({
selector: 'json-fetcher-example',
templateUrl: './JsonFetcherExample.html'
})
export class JsonFetcherExample {
constructor(private json: JsonFetcherService) {
this.json.fetch('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
}
}
Update:
In addition to addressing the binding issue with this
, it is important to note that the subscribe method used here is asynchronous. To ensure correct execution after fetching the JSON file, the relevant code should be moved inside the callback function.
public fetch(url: string, myFunction) {
const test = this.http.get(url);
test.subscribe((data)=> {
this.data = data;
myFunction();
});
}