Hi i am getting the following response from server
{
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
}
i need to show a message based on the status , we are using angular and javascript i am unable to loop through and read the same, any help would be appreciated
The simpliest version i can imagine:
<script>
var json = {"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}};
for(var t in json)
console.log(json[t]['status']);
</script>
You can read the values by parsing the string as json:
var obj = JSON.parse('{"Application1":{"status":"SUCCESS","comment":"A123456 added successfully to Application"},"Application2":{"status":"SUCCESS","comment":"B67890 added successfully to Application"}}')
Then you can get access the values as properties:
obj.Application1.status
First check the response is JSON object or string. If it is string, parse it to JSON. Then you can loop through it.
Use the following functions
isJson(your_response);
will return the JSON object or null.
var whatIsIt = function (object) {
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = {}.constructor;
if (object === null) {
return "null";
}
else if (object === undefined) {
return "undefined";
}
else if (object.constructor === stringConstructor) {
return "String";
}
else if (object.constructor === arrayConstructor) {
return "Array";
}
else if (object.constructor === objectConstructor) {
return "Object";
}
else {
return "don't know";
}
};
var isJson = function(o1)
{
// Validate JSON strings
var json_object = null;
var type = whatIsIt(o1);
switch(type)
{
case "String":
try{
json_object = JSON.parse(o1);
}catch (e){
return null;
}
break;
case "Object":
try {
JSON.stringify(o1);
json_object = o1;
}catch (e) {
return null;
}
break;
}
return json_object;
};
Assuming that the communication with the server is carried out in a separate angular service, you need to use ng-repeat and ng-if directives,
Please find the JSFiddle here :
http://jsfiddle.net/2ju3c6tc/1/
var module = angular.module("myModule", []);
module.service('serverCommunicator', ['$http',
function($http) {
//code to get the data from the server
//server Data would hold the JSON object after the AJAX req,however, it is assigned manually over here
this.serverData = {
"Application1": {
"status": "SUCCESS",
"comment": "A123456 added successfully to Application"
},
"Application2": {
"status": "SUCCESS",
"comment": "B67890 added successfully to Application"
}
};
}
]);
module.controller('myController', ['$scope', 'serverCommunicator',
function($scope, serverCommunicator) {
$scope.serverData = serverCommunicator.serverData;
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController as myCont">
<div ng-repeat="dataElement in serverData">
<div ng-if="dataElement.status=='SUCCESS'">
This is success message :{{dataElement.comment}}
</div>
<div ng-if="dataElement.status=='FAILURE'">
This is failure message {{dataElement.comment}}
</div>
</div>
</div>
</div>
Related
I am trying to build out an API endpoint within Workato using a Javascript plugin. Part of the requirement is to validate if the JSON request is valid based on the schema that I defined.
Specifically, I need to throw a 400 Bad Request error if a required field is not provided or if the provided value does not match the expected data type (e.g. string when expecting number).
My original thought was to define a "checkRequest" function that will intake the JSON request object with every possible data point and essentially run through a huge list of if/else if /else conditions to test every value for "null" and use "type of" to test for data type and then return if I encounter an error.
However, note that the schema is HUGE with about 100 different data points and consists of nested objects within objects so I was hoping to find the most optimized way to iterate rather than relying on a bulk of if statements.
See my code below and a snippet of a request based on the schema (can't share full schema):
My code:
function checkRequest({
partner_id,
merchant_reference_id,
optional_string,
}) {
let response = {
validRequest: true,
responseStatus: "",
errorTitle: "",
errorDetail: "",
errorCode: "",
};
let badRequestTitle = "Bad Request";
let requiredFieldErrorDetail = (field) => {
return field + " is a required field but was not provided in request.";
};
let wrongFormatErrorDetailDetail = (field, inputDataType, expectedDataType) =>
field +
" expected data type is " +
expectedDataType +
", but " +
inputDataType +
" was received.";
//partner_id
if (partner_id == "" || partner_id == null) {
response.validRequest = false;
response.errorDetail = requiredFieldErrorDetail("partnerID");
console.log(response);
return response;
} else if (typeof partner_id != "string") {
response.validRequest = false;
response.responseStatus = "400";
response.errorCode = "40001";
response.errorTitle = badRequestTitle;
response.errorDetail = wrongFormatErrorDetail(
"partnerID",
typeof partner_id,
"string"
);
console.log(response);
return response;
}
//merchant_reference_ID
else if (merchant_reference_id == "" || merchant_reference_id == null) {
response.validRequest = false;
response.errorDetail = requiredFieldErrorDetail("partnerID");
console.log(response);
return response;
} else if (typeof merchant_reference_id != "string") {
response.validRequest = false;
response.responseStatus = "400";
response.errorCode = "40001";
response.errorTitle = badRequestTitle;
response.errorDetail = wrongFormatErrorDetail(
"partnerID",
typeof merchant_reference_id,
"string"
);
console.log(response);
return response;
}
//else
else {
console.log(response);
return response;
}
}
let requestBody = {
partner_id: "",
merchant_reference_id: "aa",
optional_string: "3",
};
checkRequest(requestBody);
Sample request snippet (assume that some fields are required and others are optional):
{
"application": {
"partnerReferral": {
"partnerID": "mg3e09f8-a8dd-44e6-bb06-55293b799318",
"merchantReferenceID": "mg3e09f8a8dd44e6bb06-55293b799318"
},
"businessInformation": {
"identity": [
{
"identifier": "EMPLOYER_IDENTIFICATION_NUMBER",
"value": "77-1122333"
}
],
"businessType": "ASSOCIATION",
"classification": {
"code": "SIC",
"value": "string"
}
}
}
}
Hoping to rely on vanilla Javascript to accomplish this is the best way possible, but open to plugins if necessary.
I have the following code in which I fetch data from the JSON file , I Store data in $scope.users variable, But I want to fetch only username value how can I do this?
LoginCtrl.js
'use strict';
angular.module('User').controller('LoginCtrl', ['$scope','$state', "SettingService","UserService", function($scope,$state, SettingService,UserService) {
$scope.users = [];
UserService.getLoginInfo().then(function(response){
$scope.users = response.data.data["username"];
}, function(error){
})
var vm = this;
vm.doLogin = function(){
var username = document.forms["loginForm"]["email"].value;
var password = document.forms["loginForm"]["password"].value;
if(username == "admin#gmail.com" )
{
if(password == "admin")
{
$state.go('app.home');
}
}
};
}]);
User.json
{
"result": "success",
"data": [
{ "id": 1, "username":"admin#gmail.com", "password":"admin"}
]
}
you can get value for that JSON value as
response.data.data[0]["username"]
If you want to get all the usernames from the array, then you can do something like this:
var arr = response.data.map(function(a, b){
return a.username;
});
arr will contain all the username details
I am currently working on an app using firebase and angularJS (ionic). Basically this is a car management app, so you have people sharing their cars with others. I tried to structure the data as flat as possible to be efficient. My issue here is that if without problem I can display the list of the car_id of the different cars shared with the logged user, I can't find a way to display the list of cars shared with the user displaying the year and the model.
Thank you in advance for your help !
{
"rules": {
"users": {
".write": true,
"$uid": {
".read": "auth != null && auth.uid == $uid"
},
"cars": {
"car_id":true,
"role":true // Owner, borower...
}
},
"cars": {
"car_id":true,
"model":true,
"year":true
}
}
}
carapp.controller("carsController", function($scope, $firebaseObject, $ionicPopup, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.list = function() {
frbAuth = frb.getAuth();
if(frbAuth) {
var userObject = $firebaseObject(frb.child("users/" + frbAuth.uid));
userObject.$bindTo($scope, "user");
$scope.cars = frb.child("cars");
}}
$scope.createCar = function() {
$ionicPopup.prompt({
model: 'Create a new car',
inputType: 'text'
})
.then(function(result) {
if(result !== "") {
var newCar = $scope.cars.push({
model: result
})
var newCarId = newCar.key();
$scope.user.cars.push({car_id: newCarId, role: "owner" });
} else {
console.log("Action not completed");
}
});
}
});
<div class="list">
<a ng-repeat="car in user.cars" >
<h2>{{car.car_id}}</h2> ----> works fine !
<h2>{{car.model}}</h2> ----> How to get this working ?
<h2>{{car.year}}</h2> ----> How to get this working ?
</a>
</div>
In the users/ path, begin by storing the list of cars by index, instead of in an array. So your structure would be:
{
"users": {
"kato": {
"cars": {
"DeLorean": true
}
}
},
"cars": {
"DeLorean": {
model: "DeLorean",
year: "1975"
}
}
}
To join this using AngularFire, you have several approaches available. An AngularFire-only solution might look like this, taking advantage of $extend:
app.factory('CarsByUser', function($firebaseArray) {
return $firebaseArray.$extend({
$$added: function(snap) {
return new Car(snap);
},
$$updated: function(snap) {
// nothing to do here; the value of the index is not used
},
$$removed: function(snap) {
this.$getRecord(snap.key()).destroy();
},
// these could be implemented in a manner consistent with the
// use case and above code, for simplicity, they are disabled here
$add: readOnly,
$save: readOnly
});
var carsRef = new Firebase(...).child('cars');
function Car(snap) {
// create a reference to the data for a specific car
this.$id = snap.key();
this.ref = carsRef.child(this.$id);
// listen for changes to the data
this.ref.on('value', this.updated, this);
}
Car.prototype.updated = function(snap) {
this.model = data.model;
this.year = data.year;
}
Car.prototype.destroy = function() {
this.ref.off('value', this.meta, this);
};
function readOnly() { throw new Error('This is a read only list'); }
});
app.controller('...', function($scope, CarsByUser, authData) {
// authenticate first, preferably with resolve
var ref = new Firebase(...).child(authData.uid);
$scope.cars = CarsByUser($scope);
});
For a more sophisticated and elegant approach, one could utilize NormalizedCollection and pass that ref into the AngularFire array:
app.controller('...', function($scope, $firebaseArray) {
var ref = new Firebase(...);
var nc = new Firebase.util.NormalizedCollection(
ref.child('users/' + authData.uid),
ref.child('cars')
)
.select('cars.model', 'cars.year')
.ref();
$scope.cars = $firebaseArray(nc);
});
I am currently working on an app using firebase and angularJS (ionic). Basically this is a car management app, so you have people sharing their cars with others. I tried to structure the data as flat as possible to be efficient. My issue here is that if without problem I can display the list of the car_id of the different cars shared with the logged user, I can't find a way to display the list of cars shared with the user displaying the year and the model.
Thank you in advance for your help !
{
"rules": {
"users": {
".write": true,
"$uid": {
".read": "auth != null && auth.uid == $uid"
},
"cars": {
"car_id":true,
"role":true // Owner, borower...
}
},
"cars": {
"car_id":true,
"model":true,
"year":true
}
}
}
carapp.controller("carsController", function($scope, $firebaseObject, $ionicPopup, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.list = function() {
frbAuth = frb.getAuth();
if(frbAuth) {
var userObject = $firebaseObject(frb.child("users/" + frbAuth.uid));
userObject.$bindTo($scope, "user");
$scope.cars = frb.child("cars");
}}
$scope.createCar = function() {
$ionicPopup.prompt({
model: 'Create a new car',
inputType: 'text'
})
.then(function(result) {
if(result !== "") {
var newCar = $scope.cars.push({
model: result
})
var newCarId = newCar.key();
$scope.user.cars.push({car_id: newCarId, role: "owner" });
} else {
console.log("Action not completed");
}
});
}
});
<div class="list">
<a ng-repeat="car in user.cars" >
<h2>{{car.car_id}}</h2> ----> works fine !
<h2>{{car.model}}</h2> ----> How to get this working ?
<h2>{{car.year}}</h2> ----> How to get this working ?
</a>
</div>
In the users/ path, begin by storing the list of cars by index, instead of in an array. So your structure would be:
{
"users": {
"kato": {
"cars": {
"DeLorean": true
}
}
},
"cars": {
"DeLorean": {
model: "DeLorean",
year: "1975"
}
}
}
To join this using AngularFire, you have several approaches available. An AngularFire-only solution might look like this, taking advantage of $extend:
app.factory('CarsByUser', function($firebaseArray) {
return $firebaseArray.$extend({
$$added: function(snap) {
return new Car(snap);
},
$$updated: function(snap) {
// nothing to do here; the value of the index is not used
},
$$removed: function(snap) {
this.$getRecord(snap.key()).destroy();
},
// these could be implemented in a manner consistent with the
// use case and above code, for simplicity, they are disabled here
$add: readOnly,
$save: readOnly
});
var carsRef = new Firebase(...).child('cars');
function Car(snap) {
// create a reference to the data for a specific car
this.$id = snap.key();
this.ref = carsRef.child(this.$id);
// listen for changes to the data
this.ref.on('value', this.updated, this);
}
Car.prototype.updated = function(snap) {
this.model = data.model;
this.year = data.year;
}
Car.prototype.destroy = function() {
this.ref.off('value', this.meta, this);
};
function readOnly() { throw new Error('This is a read only list'); }
});
app.controller('...', function($scope, CarsByUser, authData) {
// authenticate first, preferably with resolve
var ref = new Firebase(...).child(authData.uid);
$scope.cars = CarsByUser($scope);
});
For a more sophisticated and elegant approach, one could utilize NormalizedCollection and pass that ref into the AngularFire array:
app.controller('...', function($scope, $firebaseArray) {
var ref = new Firebase(...);
var nc = new Firebase.util.NormalizedCollection(
ref.child('users/' + authData.uid),
ref.child('cars')
)
.select('cars.model', 'cars.year')
.ref();
$scope.cars = $firebaseArray(nc);
});
I need to make a new object out of a multiple record parse.com object in javascript.
This is how I get the entire fetched object:
function(articleID, callback) {
"use strict";
var Comment = Parse.Object.extend('Comment');
var query = new Parse.Query(Comment);
query.descending('createdAt');
query.equalTo('commentFor', {__type:"Pointer", className:"Article", objectId:articleID});
query.equalTo('commentApproved', true);
query.find().then(function(results) {
callback(results);
}, function(error){
callback({error: error});
});
}
Now, the problem is, that this returns (callback()) an object which contains some sensitive data, such as the emails of all commenters, so I want to return a new object with, say, just 'name', 'date', and 'comment'. I just don't know how to build an object like this with a multiple record object as the master.
I am making this in node.js, if that helps in any way.
I'd like something along the line of
[
{
"name": "Robert",
"date": "2016-01-18T17:59:27.378Z",
"comment": "Hello World!"
},
{
"name": "Bob",
"date": "2016-01-15T16:37:35.226Z",
"comment": "Bees knees"
}
]
I've tried this, but it doesn't seem to work - I don't get the output I'd expect:
var test = function(articleID, callback) {
"use strict";
var Comment = Parse.Object.extend('Comment');
var query = new Parse.Query(Comment);
query.descending('createdAt');
query.equalTo('commentFor', {__type:"Pointer", className:"Article", objectId:articleID});
query.equalTo('commentApproved', true);
query.find().then(function(results) {
var object = {};
for(var i = 0; i < results.length; i++) {
object += {
commentName: results[i].get('commentName'),
commentWebsite: results[i].get('commentWebsite'),
commentContent: results[i].get('commentContent'),
createdAt: results[i].get('createdAt')
};
}
callback(object);
}, function(error){
callback({error: error});
});
};
And then I discovered query.select()
This is a case of RTFM! https://parse.com/docs/js/guide#queries-query-constraints