Loading XML File with Angular - javascript

I have Web Api calls that I make via angular $http , What I need to do are some various options.
Call Web Api endpoint which will then create an XML file on the file system of which I need to be able to have my Angular application display the XML in another window - would this be done a specific way with angular?
Like to Also be able to stream in memory the xml to be in angular as a string for me to decide how to parse thoughts?
I do see code like below, which is "nice" , but I don't want to just convert xml to json
angular.module('myApp',[]).factory('DataSource', ['$http',function($http){
return {
get: function(file,callback,transform){
$http.get( file, {transformResponse:transform} ).
success(function(data, status) {
console.log("Request succeeded", data);
callback(data);
}).error(function(data, status) {
console.log("Request failed " + status);
});
}
};
}]);
var AppController = function($scope,DataSource) {
var SOURCE_FILE = "timer.xml";
xmlTransform = function(data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.TimerStatus;
};
setData = function(data) {
console.log("setdata", data);
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE,setData,xmlTransform);
};

Related

Read JSON data in Angular JS script and use that data further in JS only

I have searched it a lot , in all cases , they usually want to show it on HTML directly , but my purpose is to use the data in Angular JS only.
angular.module('myApp').factory('UserService', ['$http', '$q', function($http, $q){
var url ;
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
//alert(JSON.stringify(url.data));
});
//var REST_SERVICE_URI = 'http://localhost:8080/HomeAccessService-1/user/';
var REST_SERVICE_URI = JSON.stringify(url.data);
var factory = {
fetchAllUsers: fetchAllUsers,
createUser: createUser,
updateUser:updateUser,
deleteUser:deleteUser
};
return factory;
function fetchAllUsers() {
var deferred = $q.defer();
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
I want to use this url data in other methods , the data is actually a REST API URL which i put in data.json file
{"data":"http://someotherip:8080/Service/user/"}
It shows object Object when alert ,
I dont want to show it in HTML but to use the data in angular js methods.
Alert is showing up before your response reach. Put alert inside request promise. You will get the response.
and use json.stringify(response.data) to make a json string
You should call the alert inside the promise otherwise it will be undefined when you alert it,
$http.get('/Service-1/static/js/data.json').then(function(response) {
url = response.data;
alert(JSON.stringify(url.data));
});*/
Inorder to display the correct data, you should use JSON.stringify()
alert(JSON.stringify(url.data));
You can do one of the two things
1. Add REST_SERVICE_URI = .. instead of that alert statement OR
2. Add those geturl call inside fetchAllUsers function and then do your next steps once you get resopnse.data
//// Add url part inside get response
var url;
var REST_SERVICE_URI;
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
REST_SERVICE_URI = JSON.stringify(url.data);
});
...
//// OR do it in sync
function fetchAllUsers() {
var deferred = $q.defer();
$http.get('/HomeAccessService-1/static/js/data.json').then(function(response) {
url = response.data;
REST_SERVICE_URI = JSON.stringify(url.data);
$http.get(REST_SERVICE_URI)
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching Users');
deferred.reject(errResponse);
}
);
});
return deferred.promise;
}
$scope.jsondata=json.stringify(response.data)
console.log(jsondata.url);
take all the json in one javascript variable then travarse that using loop or variable like jsondata.url and use it in ur future api call.

Passing JSON data with request using $http.get() or $http.post()

I'm trying to call a webservice that requires me to pass a JSON object to it. Though I'm not sure whether I'm doing it right. My service does the following:
this.updateAddressDetails = function (address, personId) {
var url = 'http://213.456.123.456:8080/Address?' +
'action=updateAddress' +
'&personId=' + personId +
'&address=' + JSON.stringify(address);
return $http.get(url);
}
But I get the following error server side (I'm using Java Servlets):
Error parsing HTTP request header
Which leads me to assume that I'm not passing the JSON to the server the correct way. Any tips?
Try something like this if your are working with angular JS:
$scope.myFunc = function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};

Using Node/Angular, how do I make a call to an api (using methods from a node module) and have the data sent to the scope?

I am trying to use angular + node and am making a method call to a JS Api.
It returns data in my index.js file that I want to be made available in my angular module for attachment to the $scope.
My two approaches/attempts have been to:
1) Inject the hiw-api module as a factory parameter (won't work/how do won't pick up my module.
2) Use RequireJS to include node module hiw-api (too complex)
My goal is that once the data is in the $scope I can manipulate it, I just can't seem to get it there. Any help would be greatly appreciated! index.js Github, index.html (if you dare)
var hiw = require("hiw-api");
var apiKey = "da45e11d07eb4ec8950afe79a0d76feb";
var api = new hiw.API(apiKey);
var http = require("http");
exports.index2 = function (req, res) {
var rawresponse;
var founderror;
var indicatorDescription;
var locales;
//var allinidcatorsURL = '/Indicators/ { page }?Key= { key }';
//var filter = new hiw.Filter()
// .addEqual(hiw.Locale.Fields.ScriptFullName, "Arkansas");
hiw.Synchronizer.sync([
hiw.IndicatorDescription.getByID(279, api, function (data, response, error) {
indicatorDescription = data;
console.log(indicatorDescription.fullDescription);
console.log(indicatorDescription);
title = "Express"; //response: rawresponse, error: founderror
}),
hiw.Locale.getAll(api, function (data, response, error) {
locales = data; //Array of Locale
//console.log(locales);
})
], function (data) {
res.sendfile('./views/index.html');
//res.json(locales);
});
};
Assuming you have the HIWmethods defined as a service correctly, you have to inject it in the controller like this:
.controller('mainController', ['$scope', 'HIWmethods', function($scope, HIWmethods) {
$scope.formData = {};
$scope.loading = true;
// GET =====================================================================
// when landing on the page, get all todos and show them
// use the service to get all the todos
$scope.test = "Hello world!!!!!!!!!!"
HIWmethods.getLocales().then(function(data) {
$scope.locales = {
availableOptions: data
}
$scope.loading = false;
});
}]);

When I “Pull to refresh”, How I clean the Cache? With Ionic Framework and AngularJS

I have a problem, I'm using a JSON coming from an external server, but when I do "Pull to refresh" or when I open the application, displays the same information I downloaded the first time the application is opened. It may be that the JSON is being stored in the cache and therefore not update? For if when I go to on-refresh = "doRefresh ()" and called another JSON, (the first time I do), update, but re-enter the application I load the information from the first JSON and if I want update, showing me the information I also downloaded the first time. This will fix manually deleting the application data, but it is not the best way ...
This is my services.js
angular.module('starter.services', ['ngResource'])
.factory('NotasService', ['$http',
function ($http) {
var items_nota = [];
var items_nota_array;
return {
all: function () {
return $http.get('http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30')
.success(function(data, status, headers, config){
console.log("**** SUCCESS ****");
console.log(status);
})
.error(function(data, status, headers, config){
console.log("**** ERROR ****");
console.log(status);
})
.then(function(response){
console.log("**** THEN ****");
items_nota = response;
return items_nota;
}
)
},
get: function (notaId) {
// Simple index lookup
var pepe = parseInt(notaId);
var ESTO = 0;
var addToArray = true;
for (var i = 0; i < items_nota.length; i++) {
if (items_nota[i].id == pepe) {
addToArray = false;
ESTO = i;
}
}
return items_nota[ESTO];
}
}
}])
This is my controller.js..
.controller('ActulidadCtrl', function ($q, $scope, NotasService, $timeout) {
var items_nota;
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Pull tu refresh
$scope.doRefresh = function () {
console.log('Actualizando!');
$timeout(function () {
//NotasService.loadData().then(function (data) {
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
})
Thanks! And Happy New Year!
UPDATE: solved the problem was in the server side cache
I think your problem is with GET query:
http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30
Please check if this query is returning same posts event if you add new data.You can make sample http query using tools like Postman.
post_status and posts_per_page are constant.
Please check. Good luck!!

Getting Json data in the Angularjs Scope

This is my first attempt at using Angularjs framework. I am trying to follow this example: http://jsfiddle.net/SAWsA/11/
I am successfully able to get the data in the Json format and it works fine.
json data:
[{"Activity_Matrix_ID":"163","Activity_ID":"131","Activity_Date":"2062-02-16","Activity_Category":"Maintanence","Activity_Project":"All Projects","Activity_Description":"Json data ","Activity_Hours":"2"},{"Activity_Matrix_ID":"161","Activity_ID":"129","Activity_Date":"2044-02-25","Activity_Category":"Tech Support","Activity_Project":"All Projects","Activity_Description":"Dummy dummy ","Activity_Hours":""}]
So basically, I want to load the data in $scope.items. I am not sure if it is the good method. I can visit the url and the data looks fine. I am stuck at getting the json correctly from the URL to the angular scope.
I tried following
<script type="text/javascript">
var sortingOrder = 'Activity_Projects';
</script>
<script>
function ctrlRead($scope, $filter) {
$scope.myData = function(item, event) {
var responsePromise = $http.get({method: 'GET', url: 'https://url_root_same_domain/timesheet/timesheet_info_table_json.php'}).success(function(data, status, headers, config) {
$scope.items = data;
console.log(data);
}).
error(function(data, status, headers, config) {
alert("No data");
});
}
</script>
Try this:
var responsePromise = $http.get('https://url_root_same_domain/timesheet/timesheet_info_table_json.php').success(...rest of your code here
The $http.get() function's first argument is a URL; not an object; and the method of a get call is already get, so you shouldn't have to do any other changes.

Categories

Resources