Struggling to manage the unforeseen error in Angular 2+ framework

Testing a new functionality where I can upload a JSON file to post data into a textarea. Additionally, I am able to manually input the JSON structure and transfer it to another textarea with removed whitespace and new lines successfully. However, encountering an issue when entering normal text and pressing enter, causing an unexpected token error.

Here is the JSON structure being used:

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c596acaba6a0b7a085a4b5b7aca9eba7acbf">[email protected]</a>",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
]

Find my Stack Blitz code here: https://stackblitz.com/edit/angular-zgyxet

If attempting to input plain text, an error occurs. How can I handle this error effectively and provide an alert to the user?

Answer №1

An error message is being generated by the JSON.parse() method because attempting to parse a regular string to JSON format will not work.

To handle this issue, it is recommended to place the JSON.parse() method inside a try/catch block like so:

test() {
    var data = this.TextData;
    var dataInfo = data.replace(/\s+/g, '').trim();
    var info = '';
    try {
        var info = JSON.parse(dataInfo);
    } catch(e) {
        alert('There was an error while parsing the JSON');
    }

    this.TextData1 = info;
}

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

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

Type in the input box using JavaScript within an HTML document

With a website containing a text box next to several buttons, the goal is for users to click on a button and have specific text populate the text box before submitting the form. An example of this setup in code form: <form action="send.php" method="pos ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Collaborating on code between a Typescript React application and a Typescript Express application

Struggling to find a smart way to share code between two interconnected projects? Look no further! I've got a React web app encompassing client code and an Express app serving as both the API and the React web app host. Since I use Typescript in both ...

The value of 'useFonts' cannot be changed as it is a read-only property in expo-fonts

Struggling with 'useFonts' being read-only and unable to assign In my Expo project using React Native (TypeScript), I encounter the issue of trying to import a .ttf font file. My attempt was to create a custom hook called "useFont" to pre-load ...

What purpose does sending null to XMLHttpRequest.send serve?

Have you ever wondered why send is often called like this? xhr.send(null) instead of just xhr.send() ? W3, MDN, and MSDN all mention that the argument is optional. Additionally, the ActiveX control seems to work without it: hr=pIXMLHTTPRequest.Create ...

Identifying the precise image dimensions required by the browser

When using the picture tag with srcset, I can specify different image sources based on viewport widths. However, what I really need is to define image sources based on the actual width of the space the image occupies after the page has been rendered by th ...

Steps to implement the click functionality on the alert controller and modify the language in Ionic 4

I am currently developing a multilingual Ionic 4 app and have implemented the alert controller to display language options. However, I am facing an issue on how to dynamically change the language based on user selection. Below is my app.component.ts code ...

In Angular 2, the routerLink feature appears as regular text on the screen

Recently, I encountered an issue with routerLink in my Angular 2 project. I am currently using Visual Studio 2015 to develop a Single Page Application with routing functionality. However, I noticed that when I click on an anchor tag with [routerLink], it d ...

How can I bring in a node module or JavaScript file without relying on webpack when working with create-react-app?

I've been facing a challenge while trying to link an external JavaScript file (server.js) with my index.js file in create-react-app. The issue arises because the server.js file utilizes the npm zeromq node module, which seems to have compatibility pro ...

Utilizing generic functions as arguments in other functions

Imagine if I were to create a type called CoolType in this manner: type CoolType<T> = {message: string, result: T} Next, let's define a type called CoolFunction which represents a function that returns CoolType: type CoolFunction = <T>( ...

Are there any @types available for browser extension objects that are interoperable?

I am in the process of developing a browser extension that would work seamlessly on Edge, Chrome, and Firefox by utilizing Typescript. After coming across an article discussing interoperable browser extensions, I stumbled upon a code snippet: window.brow ...

Transforming JSON objects, retrieve an empty value in place of undefined

Can someone please offer some advice on the following: I am retrieving JSON data using this code snippet: $.getJSON(jsonPath, function(returnedData){ ... }); The JSON object returned will have a structure similar to this: ... "skin": { "elapsedTextCo ...

Blur effect in CSS and JavaScript applied around the cursor

I am embarking on the journey of creating a website completely from scratch using html, css, and js with jQuery and other necessary libraries. My goal is to have all the code easily transferable and executable without the need for additional plugins or scr ...

Search for the ID of the currently active tab

I am looking to implement a feature that saves the current tab on postback. Here is what I need: 1) How do I determine the id of the current tab? 2) How can I pass this id to a hidden variable? Keep in mind that I cannot use jQuery tabs due to certain is ...

Using setAttribute does not function properly with ngModel within Angular framework

I am attempting to automatically assign ngModel while creating an HTML element. Here is my code: productName.setAttribute('[(ngModel)]', `customProductName`); However, I am encountering the following error: Failed to execute 'setAttribute ...

changing the default property value within an object

I'm looking to send an ajax request to a PHP file that will retrieve a user's information in JSON format. I then want to take this data and assign it to a property within an object. For example: User = { prop1: '' } I simply need to ...

Sharepoint - Results from REST API Query returning an undefined field

Utilizing REST/JS calls to populate specific fields from a particular list item has presented some challenges for me. The issue arises when attempting to retrieve certain fields, as they are showing up as undefined in the displayed results. Upon examinatio ...

What are the downsides of using PHP redirects instead of JavaScript redirects, given that most large websites opt for the latter?

After closely examining the source codes of redirect pages on several major websites that redirect to their sponsors, I found an interesting pattern. Out of the five websites analyzed, four were using different Javascript redirects: <script type="text ...

"Encountering a black screen when connecting a camera to a GLTF object in Three.JS

Hey guys, I've been working with Three.JS and I've run into a bit of trouble with the camera. I'm trying to attach the camera to an imported model object, and it seems like it's attaching but there are some issues. The shadows seem to b ...