Import a JSON file into Angular 8 and parse its contents

My code is intended to read and upload a JSON file (ARM template), but I am encountering an issue where this.updateObj appears as undefined in the console.log. Below is my code:

onChange(fileList: FileList): void {
    var file = fileList[0];
    var fileReader = new FileReader();
    var newFile = {};
    fileReader.readAsText(file, 'UTF-8');
    fileReader.onload = () => {
      newFile = fileReader.result as object;
      this.updateObj = cloneDeep(newFile);
    };
    console.log('updateObj', this.updateObj);
}

Any insight or suggestions on how to resolve this problem are greatly appreciated.

Answer №1

Your query is a bit unclear, but I believe this response should provide some clarity.

In the future, it would be beneficial to create a Minimal Reproducible Example (MRE) to assist others in assisting you more effectively.

.ts

  updateObj: any;
  onChange(event: any): void {
    var file = event.target.files[0];
    var fileReader = new FileReader();
    fileReader.readAsText(file, "UTF-8");
    fileReader.onload = () => {
      const newFile = fileReader.result as string;
      this.updateObj = JSON.parse(newFile);
    };
  }

.html

<input type="file" (change)="onChange($event)" />

<pre><code>{{updateObj | json}}</code></pre>

Using Stackblitz can greatly facilitate creating MREs for Angular-related queries.

Check out this Stackblitz example

UPDATE

@DnyaneshSurya Thank you for providing the MRE. Although your example works, it's still not entirely clear what your goal is. Note that `ngOnInit` is only called once during component initialization, thus causing the initial value of your `Input` to be undefined. If you need to perform actions when the value updates, consider using a getter/setter on the `armTemplate` property.

Here's another Stackblitz example for demonstration purposes.

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

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

How to display a conditional component in a single line with Material UI

I'm facing an issue with a component that is being reused multiple times. Here's the current output: |MyComponent1| |MyComponent2| Specifically, my condition is: if (a == 'One' || b == 'Two'){ <MyComponent data={data}/> ...

Sharing multiple object data using socket.io in express

I was able to successfully post single data using socket.io, but when I try to add another (timestamp), nothing shows up on the screen. app.js app.post('/update', function(req, res, next){ io.sockets.emit("update", req.body); io.sockets ...

Unveiling the types of an object's keys in Typescript

I am currently utilizing an object to store a variety of potential colors, as seen below. const cardColors = { primaryGradientColor: "", secondaryGradientColor: "", titleTextColor: "", borderColor: "&quo ...

Error code 1 occurs when attempting to execute the "npm run start" command

Every time I attempt to execute "npm run start" within my project folder, the following error message pops up: myLaptop:app-name userName$ npm run start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1a0b1b1ecafa0aca481f ...

Steps for correctly displaying a success message after clicking and copying to the clipboard:

In the process of developing a color palette, I am incorporating a clipboard icon enclosed in a Tooltip component alongside each color. The functionality involves copying the color's name to the user's clipboard upon clicking the icon. Subsequent ...

Is there a source where I can locate type definitions for Promise objects?

In the process of creating a straightforward class called Primrose, I am extending the global Promise object in order to include additional methods like resolve and reject. export class Primrose<Resolution> extends Promise<Resolution>{ priv ...

Switching button presses

http://jsfiddle.net/qVfy7/ HTML <div id='button'></div> <div id="mydiv">ko</div> JS $('#button').click(function () { $('#mydiv').text('ok'); }); CSS #button{ width:100px; he ...

Assembly of Components

As someone new to angular, I am currently in the process of building an angular2 application. My goal is to dynamically create a series of DOM components using the data provided below: // Class construct with properties sorted alphabetically export class ...

Utilizing AWS SDK (S3.putObject) to transfer a Readable stream to Amazon S3 using node.js

I am aiming to successfully send a Readable stream to S3. However, I have encountered an issue where the AWS api only seems to accept a ReadStream as a stream argument. When using a ReadStream, everything works as expected, as shown in the following code ...

Transmitting Data via Socket.io: Post it or Fetch it!

I am struggling to send data via POST or GET in socket.io without receiving any data back. My goal is to send the data externally from the connection. Take a look at the code snippets below: Server-side code: app.js io.sockets.on('connection', ...

Are there any alternatives to Google Charts for creating charts?

There is a restriction of only 2k queries per month, which I find insufficient. Are there any alternative classes, plugins, or tools that can be used to generate charts similar to those created by Google Charts? Thank you. ...

Animating the Click Event to Change Grid Layout in React

Can a grid layout change be animated on click in React? For instance, consider the following component: import { Box, Button, styled, useMediaQuery } from "@mui/material"; import Row1 from "./Row1"; import React from "react"; ...

Executing a designated assessment in Protractor

Is there a way to run a specific test scenario in my Angular app? I recently added a new feature in Protractor, created the necessary page and steps, but I already have other features implemented. I am wondering if it is possible to solely test the new f ...

Event for terminating a Cordova application

We are looking for a way to send a notification to the user's device when our app is closed rather than just paused. On iOS, this occurs when you double click the home button and swipe up on the app, while on Android it happens when you press the Men ...

There seems to be an issue with AJAX file uploading functionality in Django

I'm facing an issue with uploading files using the onchange event and AJAX. I am only able to get the file path on the backend, not the actual file itself. My goal is to modify the code so that when a PDF file is selected, it automatically gets upload ...

Is it possible to dynamically load records in real time with the help of PHP and jQuery?

I developed a custom system using PHP that allows users to post status messages, similar to a microblog. The system utilizes a database table structured like this: posts_mst ------------------ post_id_pk post_title post_content date_added Initially, I su ...

Can Ajax and jQuery be utilized on a webpage in conjunction with a cron job?

These are the steps my page performs: Retrieve an array from a different server (first.php) Parse values using a PHP script Send parsed values using an AJAX call In the next page (second.php) that is called by AJAX, perform MySQL queries If values meet c ...

What are the steps to create a connect4 board featuring rounded corners and curved sides?

How can I create a Connect4 board with the exact styles and properties shown in the image? I want to achieve the curved sides effect as displayed. Can this be done using only HTML elements, or is there an easy SVG solution available? Here is my current co ...

Enhance the information within the textextjs plugin by incorporating additional data

I am attempting to invoke a function within the textextjs method- //my function function GetAreaTags() { return "some text"; } //textext initialization $('#territory').textext({ plugins: 'tags prompt focus autocomplete ajax', ...