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

Tips on triggering a function when an Ionic or HTML event is initiated

I am facing a scenario on my HTML page where I need to display certain data when an if condition returns False, and execute a function when the condition returns true. However, I'm unsure about how to achieve this. <ng-container *ngIf="!(form.answ ...

Is there a possibility of a @types/jest version 27 coming out soon?

It appears that all Jest related packages I've come across are currently on version 27, except for this one. I wonder if there's a specific reason for this disparity. The Jest documentation mentions the importance of matching versions with associ ...

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Launching the Skeleton feature in NextJS with React integration

I have been working on fetching a set of video links from an Amazon S3 bucket and displaying them in a video player component called HoverVideoPlayer. However, during the loading process, multiple images/videos scale up inside a Tailwind grid component, ca ...

Utilizing the Redux Connect HOC's wrapped component type in React.RefObject without the need for re-importing

My current setup involves a simple component that is wrapped with react-redux and has a ref with forwardRef: true, demonstrated below: // Button.tsx class Button extends React.Component { // ... } // ... export default connect(mapStateToProps, null, n ...

Why is passing data:{} to a route essential for achieving the desired outcome?

Check out the Angular Material Documentation Site passing {} to the Homepage route: {path: '', component: HomePage, pathMatch: 'full', data: {}} I'm interested in knowing the significance of data: {}. Recent Discovery Closer ex ...

What is the best way to implement a singleton service throughout an Angular application?

I am currently working with a service that emits events: import { Subject, Observable } from "rxjs"; import { Injectable } from "@angular/core"; @Injectable({ providedIn: "root" }) export class TabEvents { private routeParameters: Subject<any> ...

How can I deploy a react-express application to Azure cloud platform?

Struggling to deploy my react-express application on Azure. The code is divided into client and server directories. Attempted deployment using Azure Static Web application but encountered failure. https://i.stack.imgur.com/ailA0.png https://i.stack.imgur.c ...

What is the best way to transfer the current index of a component that is nested within another component?

Seeking guidance on implementing a unique feature for my Hero Component, which includes a background image and a carousel. My goal is to dynamically change the background images based on the current slide visible in the carousel. However, I am facing a cha ...

Tips for customizing the list of components and attributes for each component in the Angular Form.io builder

I have successfully integrated form.io with Angular 10. After creating a demo project using form.io in the Angular CLI, I was able to develop a custom component and customize the editForm for it. import { Injector } from '@angular/core'; import ...

Guide on creating and deploying an iOS API file onto a physical device with a Mac computer

I recently switched to using a Mac and have installed Xcode successfully, along with adding the platform for iOS. However, when I use adb devices, my iPhone device is not detected, but my Android device is recognized when connected. Additionally, when ru ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Having difficulties running the updated project from Angular 4 to 6

I recently updated my Angular 4 project to Angular 6. While trying to run the project, I encountered an error. Despite searching for similar questions, I was unable to find a satisfactory answer. OpaqueToken is not a constructor. Below is a snippet ...

How can I use Typescript to define a function that accepts a particular string as an argument and returns another specific string?

I've been working on this code snippet: const Locales = { en_gb: 'en-gb', en_us: 'en-us', } as const type ApiLocales = typeof Locales[keyof typeof Locales] type DatabaseLocales = keyof typeof Locales function databaseLanguage ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...

Angular has surpassed the maximum call stack size, resulting in a Range Error

I am facing an issue while trying to include machine detail and a button bar in my app. Interestingly, this setup has worked perfectly fine in other parts of the application but is causing errors in the core module. Here is the error message main.ts impo ...

Gathering user key event input for a duration of 2 seconds before resetting it

I need help implementing a feature where I can clear the user's input text after 500ms if they are entering characters consecutively. private userInputTimer; private userInputText = ''; private handleEvent(event: KeyboardEvent): void { if ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...