Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends.
import { Component, OnInit,AfterViewInit} from '@angular/core';
import { HttpClient,HttpHeaders, HttpResponse } from '@angular/common/http';
import * as fs from 'fs';import { join } from 'path';
export interface PeriodicElement {
S_No: number;
name: string;
weight: number;
symbol: string;
}
const ELEMENT_DATA: PeriodicElement[] = [
{S_No: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{S_No: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{S_No: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{S_No: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{S_No: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{S_No: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
{S_No: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
{S_No: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
{S_No: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
{S_No: 10,name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
@Component({
selector: 'app-status-details',
templateUrl: './status-details.component.html',
styleUrls: ['./status-details.component.scss'],
})
export class StatusDetailsComponent {
dataVal:any ='';
displayedColumns: string[] = ['S_No', 'name', 'weight', 'symbol'];
dataSource = ELEMENT_DATA;
constructor(private httpClient: HttpClient) {
}
ngOnInit(): void {
};
ngAfterViewInit():void{
this.sampleTest();
}
sampleTest()
{
const url:string = 'assets/tempFile.txt'
this.httpClient.get(url, { responseType: 'blob', observe: 'response' }).subscribe((value: HttpResponse<Blob>) => {
const data = new Blob([value.body as Blob], {type: value.body?.type});
const reader = new FileReader();
reader.readAsText(data);
reader.onload = (content) => {
const textInFile = reader.result as string;
this.dataVal = textInFile;
console.log("TEST",this.dataVal)
};
});
}
}