Cordova file transfer plugin - angularjs

i am creating ionic app where i want to download a image which is dynamic and using cordova file transfer plugin but its not working kindly check where i did the mistake .
Error :- url is not defined ,Cannot read property 'split' of undefined
$
scope.downloadImage = function() {
$http.get('http://sabkideal.com/phpapi_/cashback.php').success(function(response) {
$scope.data = response;
for (var i=0 ;i <response.length; i++)
{
var url = response[i].image;
var deal = response[i].id;
//url showing the same url every time i click and not jumping to next statement when click on send image download .
console.log(deal);
console.log(url);
var filename = url.split("/").pop ;
console.log(filename);
var targetPath = encodeURI(cordova.file.dataDirectory + fileName);
console.log(targetPath);
var options = {};
var trustHosts = true;
}
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(
function(result) {
alert('Download success');
refreshMedia.refresh(targetPath);
},
function(err) {
alert('Error: ' + JSON.stringify(err));
},
function(progress) {
// progressing download...
})
});
}

Make sure the data return is not undefined. By implement the checking you can check whether the data is undefined or not. Use then instead of success because it is deprecated in Angular 1.5 and below
$http.get('http://sabkideal.com/phpapi_/cashback.php').then(function(response) {
$scope.data = response.data;
// Need to check response data so that it is not undefined
if ($scope.data !== undefined && $scope.data !== null && $scope.data !=="") {
for (var i=0 ;i <$scope.data.length; i++)
{
// Checking also need to be done here
if ($scope.data[i].image !== undefined && $scope.data[i].image
!==null && $scope.data[i].image !== "") {
var url = $scope.data[i].image;
var filename = url.split("/").pop ;
}

Related

Collect Images from Local Server(Acquia Dev Desktop)

I am try to collect data and images from local server (Acquia Dev Desktop) using this Angular Js code
controller
var app = angular.module('App', []);
app.controller('Ctrl', function($scope, $http) {
$scope.images = [];
$http({
method : "GET",
url : 'http://docroot.com.dd:8083/catalogue/11/images/json'
}).then(function mySucces(response) {
$scope.images = response.data;
}, function myError(response) {
$scope.images = response.statusText;
});
});
Json
[{"image":" <a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>"}]
// i got out put like this :
<a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>
i need to collect only image url instead of the whole link ,
Well, sending HTML elements in a JSON doesn't seem good to but, anyway if you cannot change it...
For my part, I would parse the html string with the built-in XML parser.
Here is the code taken from this answer
//XML parser
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
//should work with any recent browser
return ( new window.DOMParser()).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
//This part is intended to very old browsers
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
//Your code
var jsonContent= [{"image":" <a href=\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg\">Property Press.compressedjpg_Page1.jpg<\/a>"}];
var elem = jsonContent[0].image;
var link = parseXml(elem);
try {
document.getElementById("out").innerHTML = link.documentElement.getAttribute("href");
} catch (e) {
alert(e);
}
<span id="out" />

Return JSONP from NodeJS server with AngularJS

Im trying to implement ngInfiniteScroll - Loading Remote Data on my app.
The Demo works fine & I was successfully getting the Reddit API, but cant get my list to work.
I am successfully hitting 200 server response & can see my data in the dev tool. These answers have been some help 1 & 2 but I'm still not fully sure on what to do.
EDIT (see angular factory edit):
This callback is now working and $http is going to success however I'm now getting Cannot read property 'length' of undefined
Angular Factory:
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
// Edit - I changed this var from
// var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
// to
var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data) {
console.log(data);
var items = data.children;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i].data);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
console.log('Reddit.prototype');
};
NodeJS Route:
app.get('/list', function (req, res) {
Found.find(function (err, post) {
if ( err ) {
res.send( err );
}
res.jsonp( post );
});
});
Reddit.prototype.nextPage = function() {
if (this.busy) return;
this.busy = true;
// Edit - I changed this var from
// var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&jsonp=JSON_CALLBACK";
// to
var url = config_api.API_ENDPOINT_LOCAL + "list?after=" + this.after + "?alt=json-in-script&callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data) {
console.log(data);
var items = data;
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.after = "t3_" + this.items[this.items.length - 1].id;
this.busy = false;
}.bind(this));
console.log('Reddit.prototype');
};
Should fix it!

compare to object angular js

i have a problem with AngularJS I receive from api json that json contains a prod url and url prerpod I would make calls to these APIs to retrieve a new one json then compare the results to validate which are the same as the problem is that I have a 200 aPI test how can I do. Thank you in advance
ps I think the test objects with the method equals.
i have 100 object like this:
{
"ID": "1",
"URL_preprod": "url1",
"Preprod_bis": "url2",
"prod": "url3",
}
i need to check if the result of call is equals for each object.
function callAtTimeout() {
if ($scope.preprod && $scope.preprodBis) {
angular.equals($scope.preprod,$scope.preprodBis);
$scope.msg = "equals";
}}
$scope.test = function() {
if (tnrArray) {
for (var i = 0; i < tnrArray.length; i++) {
var urlPreprod = tnrArray[i].URL_preprod;
console.log(urlPreprod);
$http.get(urlPreprod).success( function(response) {
$scope.preprod = response;
console.log(response);
});
var urlPreprodBis = tnrArray[i].Preprod_bis;
console.log(urlPreprodBis);
$http.get(urlPreprodBis).success( function(response) {
$scope.preprodBis = response;
console.log(response);
});
$timeout(callAtTimeout, 3000);
}
var response1;
$http.get("/your/url").then(function(response) {
response1 = response;
return $http.get(response.prodUrl);
}).then(function(prodResponse) {
console.log(prodResponse);
console.log(_.isEqual(response1 , prodResponse)); // uses lodash
}).catch(function(badResponse) {
console.log("oops something went wrong", badResponse);
})
this should work - lodash is used to check for equality
TO DO THIS FOR 200 URLs ASYNCHRONOUSLY ...
var urlList = ['/path/url1','/path/url2','/path/url3'];
angular.forEach(urlList, function(url) {
var response1;
$http.get(url).then(function(response) {
response1 = response;
return $http.get(response.prodUrl);
}).then(function(prodResponse) {
console.log(prodResponse);
console.log(angular.equals(response1 , prodResponse));
}).catch(function(badResponse) {
console.log("oops something went wrong", badResponse);
})
});

how to handle multiple delete and displaying 1 message using delete service in angular JS

When i check all lists in table, and press delete button, A DELETE SERVICE will be called.(Using AngularJS)
Problem is, i am using a loop, and on successful delete and unsuccessful delete, i am getting alert multiple times.(No. of selection times)
And its not working properly, if place it out of loop because its Async Task.
Here is the code,
This is a controller which initiates a service.
$scope.confirmAction = function() {
var costsToDelete = [];
angular.forEach($scope.objects, function(cost) {
if (cost.selected == true) {
costsToDelete.push(cost);
}
});
$scope.deleted = true;
//need to put confirmation dialog here.
//URL: specific to timesheet deletion. it will be prefixed with constant url
var delRequestUrl = URLs.costsUrl + '/';
deleteService.deleteRecord($scope.objects, costsToDelete, delRequestUrl);
};
This is a service.
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
Alert('success');
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
Alert('error');
});
}
};
return deleteService; }])
I need a result like: Alert should display only once.
If all items are successfully deleted, then success or failure message.
Why dont you just create a boolean bit var status= false;//default value to true inside success callback handler and false inside error callback handler,
so once all calls are complete based on this bit you can alert success or failure
Angular JS Code:
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var statusBit = false; // status tracker
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
// Alert('success');
statusBit = true;
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
//Alert('error');
statusBit = false;
});
if(statusBit){
Alert('success'); //console.log('successfully deleted');
}
else {
Alert('error'); // console.log('error while deleting');
}
};
return deleteService; }])
.service('deleteService', ['dataService', 'Constant.urls', 'Constants','$q','alerts',function(dataService, URLs, Constants, $q, alerts) {
var deleteService = {};
deleteService.deleteRecord = function(records, listOfRecordsToDelete, url) {
var overallResult = true;
while (listOfRecordsToDelete.length > 0) {
var recordToBeDeleted = listOfRecordsToDelete.pop();
var index = listOfRecordsToDelete.indexOf(recordToBeDeleted);
var delRequestUrl = url + recordToBeDeleted.id;
var result = dataService.deleteObject(delRequestUrl);
result.success(function(data) {
records.splice(index, 1);
});
result.error(function(data, status, headers, config) {
dataService.handleError(status,data);
overallResult = false ;
});
}
};
return deleteService; }])

ngCordova get GCM regid inside a controller

I'm having troubles trying to register my GCM regid with ngCordova and $cordovaPush.
I can't manage to retrieve my regid inside my controller to send it to my API via $http:
var gcmToken;
gcmNotificationHandler = function(e) {
if (e.event === "registered") {
gcmToken = e.regid;
console.log(gcmToken);
}
};
var aTonAvis = angular.module('aTonAvis', ['ngCordova']);
aTonAvis.value('serverUrl', "http://atonavis.local/");
aTonAvis.controller('RegisterCtrl', function($scope, $cordovaPush,
$cordovaDevice, $http, serverUrl) {
var gcmConfig = {
"senderID": "00000000000"
};
var iosConfig = {
"badge": "true",
"sound": "true",
"alert": "true",
};
gcmConfig.ecb = "gcmNotificationHandler";
iosConfig.ecb = "iosNotificationHandler";
var configHandler = function() {
if ($cordovaDevice.getPlatform().toLowerCase() ===
'android' || $cordovaDevice.getPlatform() ===
'amazon-fireos') {
return gcmConfig;
} else {
return iosConfig;
}
};
this.registered = false;
document.addEventListener("deviceready", function onDeviceReady() {
$cordovaPush.register(configHandler()).then(function(
result) {
console.log("Inside register " + gcmToken);
var pushToken;
if ($cordovaDevice.getPlatform().toLowerCase() ===
'ios') pushToken = result;
else pushToken = gcmToken;
$http.post(serverUrl + 'api/setdevice', {
token: pushToken,
device: $cordovaDevice.getPlatform(),
version: $cordovaDevice.getVersion(),
model: $cordovaDevice.getModel()
}).success(function(data, status,
headers, config) {
this.registered = true;
});
}, function(err) {
console.log("Registering Error : " + err);
});
});
});
The .then function is fired before the gcmNotificationHandler so my gcmToken is undefined, and here's what I get in my logs :
Inside register : undefined app.js:41
APA91bEzVUk3T1T6WpIsEHOq43hCh_pZeBPjRDPSPxV2j6VjVW-KcUepbmf6snaCiqGvYp3H_XYHIXQdbVtvMF3t-NtoZJaJzV9FkNtUlutuWYs5XPAZ-H1ixQnAyhTO6fAPDMn7Ef5f5HgBR9fgWpmXc0u_xBM4yKvoXCnVXEG18IZV2hvY app.js:6
I don't know what I'm doing wrong here, can anybody help ?
You need to install these two cordova plugins before run the app.
Device cordova plugin: https://github.com/apache/cordova-plugin-device
cordova plugin add https://github.com/apache/cordova-plugin-device
Console cordova plugin: https://github.com/apache/cordova-plugin-console
cordova plugin add https://github.com/apache/cordova-plugin-console
http://blog.revivalx.com/2014/11/14/implement-push-notifications-for-android-and-ios-phonegap-part-3/
Here is my code that uses ngCordova with PushPlugin. The regid comes in the same callback for event 'pushNotificationReceived' for android. Here is the code I use within the callback for that event to receive the regid from GCM:
Checking for (notification.event === 'registered') is the most important.
$rootScope.$on('pushNotificationReceived', function(event, notification) {
//console.log("result: " + JSON.stringify(event));
console.log("result: " + JSON.stringify(notification));
console.log('Success: Inside the push notification received callback with this payload JSON' + notification);
if(( platform == 'android' || platform == 'Android' ) && notification.regid && (notification.event === 'registered'))
{
var googDevToken = notification.regid;
console.log(googDevToken);
}
});

Resources