I have been attempting to retrieve JSON data from a local file in the assets folder. Despite searching for solutions on Google, I have not been able to find one that works as desired.
I created a service with the following code:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class JSONService {
public JSONArr: any;
constructor(private http: HttpClient ) { }
initJSON(path: string = "") {
this.JSONArr = this.getJSONArr(path);
console.log("@ Service");
console.log(path);
console.log(this.JSONArr);
// return this.JSONArr;
}
async getJSONArr( path: string = ""): Observable<any> {
return this.http.get(path).subscribe(data => {
this.JSONArr = data;
console.log(data);
}
}
}
The path is provided from the app.component.ts The JSON looks like this
{
"title": "Testtitle",
"content": "Test Message"
}
My issue is: The console.log within the getJSONArr function correctly displays the JSON data, but the console.log within the initJSON function returns undefined
Can anyone provide assistance?