Verify JSON data from server using AngularJS

My understanding is that in Angular, the HTTP service has two checks for 'success' and 'error' when connecting to a service. I have already handled these checks as my first step.

The issue I am facing now is with the data in my JSON file. It contains a 'success' state which indicates if there are any problems with the data received from the form. In case of errors, there will be an error object that needs to be displayed to the user.

I need to check for the value of 'success', but I'm not sure where the best place to do this would be. Should it be done in the controller?

Since the correct data is essential for the page to function properly, checking for 'success' should be one of the first tasks after retrieving the data.

Here's a basic layout of the controller:

app.controller("dataCtrl", function ($scope, $http) {

$http.post('/getdata').success(function (data) {

    $scope.businessData = data;

    // Should I be checking businessData.success at this level?

}).error(function () {
    alert("Problem");
});

});

Answer №1

Here is an example of how you can handle data retrieval:

$http.post('/getdata').success(function (data) {
  if (validate(data)) {
    $scope.businessData = data;
  } else {
    $scop.buisnessDataError = {msg: 'something went wrong'};
  }
}).error(function () {..})

Alternatively, you can create your own validation function in a Promise-like style and chain promises like this:

$http.post('/getdata').then(function (res) {
   return validator(null, res.data);
}, function (err) { 
   return validator({msg: 'error'})
}).then(function (data) {
   //process your data
}, function (err) {
  alert(err.msg);
});

The validator function looks like this:

var validator = function (err, data) {
  return $q(function (resolve, reject) {
   if (/*data is not valid*/ || err) {
     reject(err);
   } else {
     resolve(data);
   }
  });
}

$q is Angular's standard implementation of Promises.

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

Transforming the XML representation of CCUserDefault into a JSON formatted string

Is there a way to transform XML data created by CCUserDefault in cocos2dx into a JSON string? Appreciate any help. ...

I have been utilizing ESBuild to compile JavaScript code for browser usage. However, I encountered an issue when trying to import CSS as I received an error message stating "Unexpected '.'". Can anyone provide guidance on how to resolve this issue?

I am currently developing a JavaScript notebook that operates within the browser environment. To compile my code, I have chosen to utilize ESBuild. My primary objective is to enable the handling of CSS imports such as <import 'bulma/css/bulma.css&a ...

Is jQuery necessary for Breeze to work in conjunction with AngularJS?

I could use some clarification on using Breeze. I've gone over the documentation but couldn't find a solution to this. If I'm incorporating Breeze with ASP MVC4 and AngularJS, do I need to load the jQuery script as well? ...

The Redis port and host remain unset despite having defined environment variables

While utilizing the redis npm package, I encountered an issue where the host and port values were showing as undefined when trying to connect. Even after checking my process.env object, I could see that the values were properly set. Strangely, it only beca ...

Increase the Speed of setInterval in JavaScript

I'm currently experimenting with gradually decreasing the interval at which a function is executed within a setInterval method. Below is a simplified example code snippet: var speed = 100; window.setInterval( speed -= 0.01 , speed); I suspect that ...

Safari experiencing hang after successful CORS OPTIONS request

Safari (10 - OSX El Capitan) Issue with CORS Encountering a problem with CORS while performing a POST request from an AngularJS front-end to a Laravel back-end. In Chrome and Firefox, both OPTIONS and POST requests return http status 200 OK In Safari 10 ...

Preventing opening while closed through the OnClick event

I have the following OnClick function: const [open, setOpen] = useState(true); and onClick={() => setOpen(!open != true)} The goal is to "close when open" and "remain closed if already closed". The current code achieves the second part but not the fir ...

Track user engagement across multiple platforms

Looking for solutions to log system-wide user activity in my Electron app. I want to track mouse-clicks and keystrokes to determine if the user is inactive for a certain period of time, triggering a timer reset within the application. I believe I may nee ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

How to access and modify the parent controller's array from a child controller within an ng-repeat iteration

I am facing a challenge where I need to perform manipulations on items within an array that is stored in a parent controller. The twist is that these manipulations have to be done from within an ng-repeat loop inside a child controller. After looking into ...

What folder layout is best suited for organizing Protractor end-to-end test cases?

Is it best practice to maintain the folder structure for e2e test cases in Protractor identical to that of the application? ...

Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I susp ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...

The React app I've been working on has a tendency to unexpectedly crash when reloading the code from time

Dealing with a frustrating issue here. I've been working on an app and for the past few weeks, it keeps crashing unexpectedly. It seems to happen more frequently after saving my code to trigger a reload, but it can also just crash randomly while navig ...

Tips for validating an email address using ReactJS

I'm currently working on customizing the email verification process for a signup form in ReactJS. My goal is to replace the default email verification with my own validation criteria. Initially, I want to ensure that the entered email address contains ...

Which version of Keycloak should I use with Keycloak-js 18.0.0 if my application is running on AngularJS 1.6.0?

When a user tries to log out from the GUI using the provided SIGNOUT button, the logout process fails and the user receives an error message stating 'Invalid parameter: redirect_uri'. Angular-js version: 1.6.0 keyCloak version: 18.0.0 ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...