Updating array values within the httpClient method in an Angular 14 application

Having trouble updating an array value using the httpClient method. I need to figure out how to access the updated array value outside of the httpclient method. Any assistance in finding a solution would be greatly appreciated.

app.component.ts:

  public allData = ['Van1', 'Hills2', 'Root3'];
  constructor(private httpClient: HttpClient) {}

  ngOnInit(): void {
     this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
     this.allData = data;
    });

    console.log(this.allData); // should display data from data.json
  }

Demo : https://stackblitz.com/edit/angular-ivy-zpvafg?file=src%2Fapp%2Fapp.component.ts

Answer №1

If you want to see the updated data, make sure to print the console log inside the httpClient subscribe function. Give it a try and witness the fresh data.

 ngOnInit(): void {
         this.httpClient.get<string[]>('../assets/data.json').subscribe((data) => {
         this.allData = data;
    console.log(this.allData); // The displayed data should be from data.json
        });
    
        
      }

Answer №2

It is important that your component does not handle any http requests directly; instead, utilize a service for this purpose.

@Injectable({...})
export class MyService {
   constructor(private http: HttpClient) {}   

   getData(): Observable<string[]> {
     return this.http.get<string[]>('../assets/data.json');
   }
}

In your component, to access the updated data list, you can either subscribe within the component:

@Component({...})
export class MyComponent implements OnInit {
  constructor(private myService: MyService){}

  ngOnInit(): void {
    this.myService.getData().subscribe(data => console.log('Response: ', data));
  }
}

Alternatively, if necessary, let the template HTML handle the response using the async pipe:

@Component({...})
export class MyComponent implements OnInit {
  theDataFromTheBackend$!: Observable<string[]>;

  constructor(private myService: MyService){}

  ngOnInit(): void {
    this.theDataFromTheBackend$ = this.myService.getData();
  }
}
<ng-container *ngIf="theDataFromTheBackend$ | async as result">
  <div> {{ result | json }} </div>
</ng-container>

Additionally, keep in mind that when subscribing to an observable, the code will execute sometime later due to it being asynchronous:

someFunction(): void {
  console.log(1);
  
  this.myservice.getData().subscribe(console.log(2));

  console.log(3);
}

The output from the above code would be 1, 3, 2

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

Custom toString() method not executed when object is created using object literal syntax

Currently, I am facing an issue with my code. I have a class called Foo which has overridden the default implementation of toString(). class Foo { bar: string; toString(): string { return this.bar; } } Whenever I create a new variable usi ...

Leveraging Expose in combination with class-transformer

I have a simple objective in mind: I need to convert the name of one property on my response DTO. refund-order.response.dto.ts export class RefundOrderResponseDto { @Expose({ name: 'order_reference' }) orderReference: string; } What I w ...

Get React-table TS up and running on your local machine using VS Code

Objective: I am trying to get React-table working with TypeScript on my local computer. Challenge: The code is based on this page https://codesandbox.io/s/gkzg3?file=/src/makeData.ts However, when I attempt to apply the code on my local computer, I ...

Can Angular 4 support the use of a "template reference variable"?

Trying to understand how to utilize a template reference variable within a .pug template. For instance: div(#var) results in an error: compiler.es5.js:1694 Uncaught Error: Template parse errors: There is no directive with "exportAs" set to "#var" (" ... ...

What steps can I take to avoid encountering the `@typescript-eslint/unbound-method` error while utilizing the `useFormikContent()` function?

Recently, I updated some of the @typescript-eslint modules to their latest versions: "@typescript-eslint/eslint-plugin": "3.4.0", "@typescript-eslint/parser": "3.4.0", After the update, I started encountering the fo ...

Developing an angular progress bar

I've been working on creating a progress bar in Angular using the mmat-stepper. Here's a snippet of my code: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppCom ...

Optimal Approach for Redirecting Authorization

I'm currently working on setting up an authorization feature for my Angular application. Here is the detailed process I am following: First, I generate a state and code in the front end. Upon clicking the login button, the application redirects to /a ...

Discovering subtype relationships in JSON with TypeScript

Consider the scenario where there are parent and child typescript objects: class Parent { private parentField: string; } class Child extends Parent { private childField: string; } Suppose you receive a list of JSON objects for both types via a R ...

Looking for help with getting ag-grid to work on Angular 2. Any new tutorials available?

Looking for a recent and effective tutorial for using ag-grid with Angular 2. The official website's tutorial is not working for me, any help would be appreciated. If anyone can provide some code examples as well, it would be really helpful. Thank y ...

Exporting the value of a module

I'm really puzzled. Here's the javascript file that's causing confusion: module.exports = { connection: 'freshairMysqlServer', tableName: 'Accounts', autoCreatedAt: false, autoUpdatedAt: false, autoPK: false, ...

Lock the table header in place as the table content scrolls upward using Angular4

Is there a way to keep the table header fixed in place while the rest of the content scrolls up? Below is a snippet from my .html file: <table class="table sticky-header"> <thead> <tr class="row-hor- ...

The following error was encountered while building Angular 2 with Webpack at src/app/userManagement/unlockUserID/unlockUserID.component.ts, on line 7

Ever since I set up my routing, I've been encountering a persistent error message: ERROR in [at-loader] src/app/userManagement/unlockUserID/unlockUserID.component.ts:7:5 I'm utilizing angular-cli and below is an excerpt from my package.json: d ...

Getting the data from the final day of every month in a Typescript time-series object array

I am dealing with timeseries data retrieved from an API that consists of random dates like the following: [ { "id": 1, "score": 23, "date": "2023-08-30" }, { "id": 2, "score&qu ...

By utilizing the HTML element ID to retrieve the input value, it is possible that the object in Typescript may be null

When coding a login feature with next.js, I encountered an issue: import type { NextPage } from 'next' import Head from 'next/head' import styles from '../styles/Home.module.css' import Router from 'nex ...

Having trouble retrieving values from a feature file in a Typescript implementation with the Cucumber Framework

Having trouble accessing values from a feature file in Typescript while using the Cucumber Framework tool Protractor. How do I retrieve these Example values in my typescript method within the When block? Here is the code for the Feature file: Feature: Na ...

Change the type of an object to a different type

Within my class, I have set the type of range to IntervalRange. export class Test {range: IntervalRange;} Then, in the parent class, I initialize the value: export class TestInitializer { Create(){ return <Test>{ range: IntervalRange.i ...

Error TS2365: The equality operator '<=' cannot be used with a string and a number

chargeCalculator() { let amount = ((document.getElementById('amount') as HTMLInputElement).value); let prescription = ((document.getElementById('prescription') as HTMLInputElement).value); let vision = ((document.getElementById('vi ...

Report on Angular code coverage for both unit and end-to-end test cases generated by the Angular CLI

Our project was built using Angular5 and CLI, but I am struggling to find a solution that gives me comprehensive code coverage for both Unit test cases and E2E test cases. For Unit test cases, we use Jasmine, and for E2E test cases, we use Protractor. Is ...

What is the best way to navigate between multiple pages in an Angular 7 application using ngIf?

In my Angular 7 app, I am facing an issue with switching between three different pages. While I have managed to switch between two of them successfully, the messages page loads in the documents section whenever I click on it. Even though I have attempted ...

A guide on leveraging typeof within function parameters to ensure accurate variances

Let's create a simple class hierarchy and a list of instances. The goal is to filter items from the list of instances based on their class. There are a couple of challenges: We cannot use the typeof T syntax. How can this be written? We cannot decla ...