Being relatively new to TypeScript and JavaScript, I am struggling with understanding how collections and file input/output operations function. Specifically, my challenge lies in retrieving data from a JSON file and storing it in a collection.
Below is the code snippet:
In my service class:
private configuration = "../../assets/Configurations/testConfiguration.json";
constructor(private http: HttpClient) {}
getBlogs(blog: string): Observable<IBlogPost[]> {
return this.http.get<IBlogPost[]>(blog);
}
getConfigurations() {
var configurationsData = [];
this.http.get(this.configuration).subscribe(data => {
configurationsData.push(data);
console.log(data);
// This successfully prints all the paths
});
//Although, this loop does not work as expected and does not print the data as if the collection is empty
configurationsData.forEach(x => console.log(x));
return configurationsData;
}
Where I inject my service class:
blogs: IBlogPost[] = [];
private blogsPaths: string[] = [];
errorMessage = "";
constructor(private appUtilityService: AppUtilityServices) {}
ngOnInit() {
//This does not populate 'blogsPaths' properly
this.blogsPaths = this.appUtilityService.getConfigurations();
this.blogsPaths.forEach(blogPath =>
this.appUtilityService.getBlogs(blogPath).subscribe(
b =>
b.forEach(blog => {
this.blogs.push(blog);
}),
error => (this.errorMessage = <any>error)
)
);
}
testConfiguration.json:
[
"../../assets/BlogPosts/testBlog1.json",
"../../assets/BlogPosts/testBlog2.json"
]
If you have any recommendations for a helpful tutorial on handling collections in JavaScript and how to efficiently return them, that would be greatly appreciated!