How to connect jsReport in AngularJS? - javascript

I have a problem now about JSReport.. It assumed that I already have an API...What I want now is how to link it with my Client Side which uses AngularJS.
If I use Postman it will return a pdf file which is what I want. But my problem is how to show it is my page when i post it using angularjs..
I have a code like this :
Controller
$scope.Print = function () {
authService.print().then(function(result){
var _result = result;
});
};
Service
var _print = function () {
var data = { "template": { "shortid": "byQtwHLPQ" } };
return $http.post("http://192.168.8.87/api/report", data).then(function (result) {
return result;
});
};
authServiceFactory.print = _print;
Now I have that Code and its not working... I assumed it has no return so I remove the return and just post but still it didn't work and even downloading the pdf didn't work on it.
Anyone can help Please...

Use like this one..
Controller
var parameter = { "template": { "shortid": "ZkMoslfdX" }};
PrintService.Print(parameter).then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
Service
var reportUrl = "http://192.168.8.87/api/report";
var _print = function (parameter) {
return $http.post(reportUrl, parameter, { responseType: 'arraybuffer' }).success(function (response) {
return response;
});
};
The main idea is that the result.data is converted into a blob and create an objectURL so that it is readable and to the object tag and $sce.trustAsResourceUrl used to trust angular to your URL
HTML
<object data="{{content}}" type="application/pdf" style="width:100%;height:80%"></object>
I refer to this post AngularJS: Display blob (.pdf) in an angular app for clarification just read that one.

Related

How to preload JSON link?

I've got a function that needs to call a link (JSON format), the fact is that I would like to be able to preload this link to smooth and reduce the operation time when calling the function.
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
colorMe(data.target)
}
});
}
function colorMe(item){
globalItem = item;
request('http://blablabla/?format=json',findMaterial);
};
function findMaterial(data){
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
function findMatchArea(areas){
jq310.each(areas, function(area) {
blablabla
The request function that I built just look if the link as been already called, so it's reloading it if true. And also send data from the link to the called function.
If you'r looking to load a static json file you should concider loading it on the top of your file. To do so you should store the datas in a global variable like that :
let datas;
request('http://blablabla/?format=json', (data) => {
datas = data
});
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
globalItem = data.target;
findMaterial();
}
});
}
function colorMe(item){
globalItem = item;
};
function findMaterial(){
const data = datas;
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
I finally found a way to do it properly, here it is :
var mylink = 'https://fr.wikipedia.org/wiki/JavaScript';
function preloadURL(link){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", link, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
return jsonObject;
};
jsonObjectInv = preloadURL(mylink);
And I just point to my json variable to parse it (really faster)
function colorMe(item){
globalItem = item;
findMaterial(jsonObjectInv);
};
Problem solved

Unit Testing Angular Js with Jasmine

I have a piece of angular code that does a post request to the cloudant, returns a response, builds a URL with it and does a get request with the same. The get request returns an array buffer through which i build a PDF file to be rendered in the front end.
Could someone please let advice me on how to unit test this as unit testing along with rest API is a new territory for me . PFB my code
$scope.viewfile = function(name) {
$http({
method : 'POST',
url : '/search/searchFiles',
data : {'currentdropdownvalue' : name} ,
}).
success(function(data){
if (!angular.isUndefined(data.docs[0])){
$scope.file = data.docs[0]._id;
var fileUrl = $scope.cloudantUrl + $scope.file +"/"+ $scope.file;
$http.get(fileUrl {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$scope.contentType = "application/pdf";
$scope.contentWords = null;
}).error(function(data){
console.log("Printing Error inside Post of view " , data);
});
}
else{
$scope.content = null;
$scope.contentWords = "File is not available for the selected Name";
}
}).
error(function(data){
console.log("Printing Error inside view " , data);
});
};
}
Ideally you should probably use $httpBackend but I usually just end up putting a spy on these functions. Heres some sudo code using spyOn:
it('Should test viewFile', function() {
spyOn($http, 'POST').andReturn(mock_data);
spyOn($http, 'GET').andCallFake(function(fileUrl) {
expect(fileUrl).toBe($scope.cloudantUrl + $scope.file +"/"+ $scope.file);
});
$scope.viewFile(mocked_name).then(function() {
expect($scope.content).toBe($sce.trustAsResourceUrl(fileURL));
expect($scope.contentType).toBe("application/pdf");
expect($scope.contentWords.toBe(null);
});
$rootScope.$apply();
});

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.

"Sandbox" for using multiple instances of a javascript lib

I'm using a js lib, which will create a global variable "AV" used everywhere in a WebApp.
But I want to create a "sandbox"(not actually a strict sandbox because of no secure concern) to use multiple different "AV"s in one WebApp.
I wrote a wrap for browser below and it works.
var AVContexts = {
App1: null,
App2: null
}
var ContextLoader = function (appId, appKey) {
this.AV = null;
this.runInThis = function (script) {
eval(this.script);
this.AV.initialize(appId, appKey);
}
this.loadContext = function (appId, appKey) {
$.ajax({
url: 'js/av.js',
dataType: "text",
context: this
}).done(function (data) {
this.script = data;
this.runInThis.call(this);
}).fail(function () {
console.log('failed');
});
}
this.loadContext(appId, appKey);
}
AVContexts.App1 = new ContextLoader(
"[appid]",
"[appkey]"
);
AVContexts.App2 = new ContextLoader(
"[appid]",
"[appkey]"
);
// Do something
var TestObject = AVContexts.App1.AV.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}, {
success: function (object) {
alert("AVOS Cloud works!");
}
});
But when I move it to nodejs. An error occurred at
this.runInThis.call(this);
ERROR: Cannot call method 'call' of undefined
Any idea?
You should cache the "this", like this:
var me = this;
before you use $.ajax. and then,
$.ajax().done(function() {
me.runInThis.call();
});
If you want to know the reason,
run
console.log(this);
before
this.runInThis.call(this);
you will know the reason.

Pass a variable to a function from another function in JavaScript (winJs)

Hi I'am working with Windows 8 app using Java Script
function fetchFromLiveProvider(currentList, globalList,value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
WinJS.xhr({url: feedUrl, responseType: "rss/json"
}).done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
});
}
function setOther(entries){
//some code here
}
I want to do is pass the entries in the fetchFromLiveProvider function to another function called setOther(entries){}. Thank you for any help...
Since WinJS.xhr returns a promise, you can do the following:
var entriesPromise = function fetchFromLiveProvider(currentList, globalList, value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
return WinJS.xhr({
url: feedUrl,
responseType: "rss/json"
});
}
function setOther(entries) {
entries.done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
//some code here
})
}
setOther(entriesPromise);

Categories

Resources