Storing data received from httpClient.get and utilizing it in the future after reading

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)
      };
    });
  }
}

Answer №1

One alternative approach is to fetch the information from a Service (using providedIn: 'root' to create a singleton that remains active and keeps the data intact) instead of a Component. After that, you can utilize the RxJs shareReplay Method to prevent unnecessary backend calls.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular routes can cause object attributes to become undefined

I am new to Angular and struggling with an issue. Despite reading numerous similar questions and answers related to AJAX, async programming, my problem remains unsolved. When I click on the 'Details' button to view product details, the routing wo ...

In order to access and showcase the current positions of each ngfor element, you need to obtain a reference to them

I am looking to retrieve references for each of the ngFor elements and display their latest Top and Left positions. Since these elements are draggable, their positions will be changing. While I can obtain a value for a single element, I am facing an issue ...

Unable to implement the `omega/theme.css` file within the angular.json configuration

"styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.css", "node_modules/primeicons/primeicons.css", ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Exploring the depths of Angular8: Utilizing formControlName with complex nested

After dedicating numerous hours to tackle this issue, I finally came up with a solution for my formGroup setup: this.frameworkForm = this.formBuilder.group({ id: [null], name: ['', Validators.required], active: [true], pa ...

Incorporate external JavaScript files into a cutting-edge Ionic 5 / Angular 9 project

I need assistance in incorporating jQuery functions into my Ionic 5/Angular 9 project. In order to access some of the functions, I have included the necessary files in the angular.json file and installed Jquery and Bootstrap through npm. However, I am un ...

Using a nodejs module is causing an error in my code

I am dealing with a module like this: module Net.Server { var socket:dgram.Socket; [...] } Here is my app.ts file: var server:Net.Server = new Server(); However, when I include this line at the beginning of the first file: import dgram = requ ...

What is the best way to set the first option in a mat-select to be

My approach to date selection involves using 3 mat-select components for day, month, and year. You can view a demo of this setup here. In an attempt to improve the code, I decided to set the initial options as null by modifying the following lines: allDat ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

Mastering the Art of Injecting Objects from the Server

Utilizing Angular Universal, I am serving my Angular application through an Express server. The objective is to embed an environment object (from the server) into my application. To achieve this, I have created an InjectionToken export const ENVIRONMENT ...

Deprecated: Ngx Progress Bar will no longer be supported due to changes in

In the scenario below, I have noticed that BrowserXhr is outdated: { provide: BrowserXhr, useClass: NgProgressBrowserXhr } But when I refer to the documentation, it directs me to the main HttpClient page without showing an alternate provider example. Wha ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

The ngOnChanges method does not fire when the input value changes

Here is an example of my Angular component: @Component({ selector: 'request-Component' templateUrls: './request.component.html' styleUrls: ['./request.component.scss'] }) export class ChildComponent implements OnIn ...

How to use Angular2 Router to redirect a state to its default substate

How can we implement a default substate in the new Angular2 Router? For instance, I would like the router to automatically direct from /user to /user/profile, creating a default substate for user. ...

Check the validity of a password using Angular's reactive forms

For my password validation using ng Reactive Forms, I have a basic html input field for the password and warning paragraphs outlining the password requirements. <div class="field"> <label class="label">Password</label ...

In Angular, how do outputs impact parents when data consistently travels down from the root?

I have a question that may seem simple, but I am really trying to understand unidirectional data flow in Angular thoroughly. If change detection always happens from top to bottom, how does @Output impact a parent component? Could I be mistaken in my assu ...

The error message "Webpack is not applying the style from leaflet.css"

Currently utilizing the ngX-Rocket angular 8 starter, I am looking to integrate the leaflet map library into my project from this source: https://github.com/Asymmetrik/ngx-leaflet After including the file in my index.html document, I encountered the follo ...

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

Tips for developing a collaborative service for utilization across numerous Angular applications

Is it feasible to develop a shared service that can be utilized in numerous Angular applications? And if so, how? For instance, similar to how we create an Angular library that can be accessed externally by packaging it into an npm package. Is it possible ...

Using Angular and Okta together can bring a seamless experience for your users. Learn how to properly use the redirect

I have integrated Okta for user authentication in my Angular 13 application. I followed the guidelines provided by Okta to utilize their SDK, but I am facing issues defining the redirectionUrl with the HashLocationStrategy. Upon logging in, I encounter a ...