I have a very simple injectable service in TypeScript for Angular 4. It fetches a JSON file as an array from the network. Afterwards, it should store the returned array in one of its properties, called data
. data
can then be accessed by other classes with the method getData()
.
My problem is that the assignment operation is ignored. Doing this.data = data
does not actually change this.data
. Everything else is working perfectly fine.
The code of 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;
}
}
The code of a very simple class that uses the 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 the issue of the binding of this
, the method used here, subscribe, is asynchronous. The code to be executed after the JSON file is fetched needs to be moved inside the callback.
public fetch(url: string, myFunction) {
const test = this.http.get(url);
test.subscribe((data)=> {
this.data = data;
myFunction();
});
}