I recently started learning Angular and am currently working on a practice app. I have a feature where the app takes in a property file as input from HTML, processes the file, and stores the values in a map using TypeScript. While I can successfully store the values in the map, I'm facing an issue accessing this map from another component.
File-reader-component.ts
export class FileReaderComponent {
static readFileAsMap(file: File): Map<string, string> {
let map :Map<string, string>= new Map<string, string>();
let fileReader = new FileReader();
fileReader.onloadend = (e) => {
// By lines
let lines = fileReader.result.toString().split('\n');
for(let line = 0; line < lines.length; line++){
if(lines[line].startsWith('#') ||
lines[line].startsWith('//') ||
! lines[line].includes('=') ) {
// invalid line - ignoring it
continue;
}
let lineArr = lines[line].split('=');
let key = lineArr[0].trim();
let value = lineArr[1].trim();
map.set(key, value);
// not checking duplicate keys to let override the config
}
};
fileReader.readAsText(file);
console.log(map);
return map;
}
}
In the code above, the console.log(map) function works correctly. However, when calling this method in another component(as shown below), it returns a map with 0 elements.
let config: Map<string, string> = FileReaderComponent.readFileAsMap(configFile);