I am using Parse inside a Meteor application. Here is my code:
HTML:
<body>
<div class="container">
<header>
<h1 style="color: red;">Meteor & Parse DB Demo</h1>
</header>
{{>header}}
</div>
</body>
<template name="header">
{{#each alphabets}}
<div class="alphabets">{{this}}</div>
{{/each}}
JS:
Parse.initialize("appid", "jsid");
var list_item=Parse.Object.extend("className");
var query=new Parse.Query(list_item);
var list=[];
if (Meteor.isClient) {
query.find({
success:function(o){
for (var i = 0; i < o.length; i++) {
var object = o[i];
list.push(object.get('name'));
console.log(list);
}
return list;
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Template.header.alphabets = function() {
return list;
};
}
</template>
The data is coming from the database, but the problem is that the template is loaded before the data arrives:
template.headed.alphabet is called before query.find is is called
Make your list a client side collection, it will then be reactive and update
list = new Mongo.Collection(null);
then do list.insert(object.get('name'))
Parse.initialize("appid", "jsid");
var list_item=Parse.Object.extend("className");
var query=new Parse.Query(list_item);
if (Meteor.isClient) {
list = new Mongo.Collection(null);
query.find({
success:function(o){
for (var i = 0; i < o.length; i++) {
var object = o[i];
list.insert(object.get('name'));
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Template.header.helpers({
alphabets : function() {
return list.find({});
}
});
}
</template>
Here is the code which worked for me i am posting this so other can refer it.
HTML:
<body>
<div class="container">
<header>
<h1 style="color: red;">Meteor & Parse DB Demo</h1>
</header>
{{>header}}
</div>
</body>
<template name="header">
{{#each alphabets}}
<div class="alphabets">{{this.name}}</div>
{{/each}}
JS:
Parse.initialize("appid", "jsid");
var list_item=Parse.Object.extend("className");
var query=new Parse.Query(list_item);
var list=[];
if (Meteor.isClient) {
query.find({
success:function(o){
for (var i = 0; i < o.length; i++) {
var object = o[i];
list.push({name:object.get('name')});
console.log(list);
}
return list;
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Template.header.alphabets = function() {
return list;
};
}
</template>
Related
The MeteorJS method "get.jade" is not returning jade object to client as expected. I'm using redis-livedata and manuel:reactivearray packages, and Redis is functioning locally correctly. I have put console.log in the code where there is a problem is returning server side data to client
jades.html
<template name="jades">
{{#if jadeslength}}
<div class="row">
<div class="user-card" id="swipe">
<img src="{{jade.img}}" style="width:100%">
<div class="card-container">
<h5>{{jade.name}}, {{jade.gender}}</h5>
</div>
</div>
</div>
<div class="row">
<div class="one-half column">
<button class="no" type="button">no</button>
</div>
<div class="one-half column">
<button class="button-primary yes" type="button">yes</button>
</div>
</div>
{{else}}
<div class="row">
<button class="button-primary search-jades" type="button" id="search">search</button>
</div>
{{/if}}
</template>
jades.js
import { Meteor } from 'meteor/meteor';
import { Session } from 'meteor/session';
import './jades.html';
Template.jades.onCreated(function () {
var jades = new ReactiveArray([]);
Session.set({'jadeId':""});
});
Template.jades.helpers({
jade: function() {
return jades.list();
},
jadeslength: function() {
var jades = jades.list();
return jades.length;
},
});
Template.jades.events({
...
'click .search-jades' () {
Template.instance.jades = [];
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var client_location = {"lat": position.coords.latitude, "lng": position.coords.longitude};
if (client_location) {
var lng = client_location.lng;
var lat = client_location.lat;
Meteor.call('client.profile', (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
var user_profile = result;
Session.set({'user_profile': user_profile});
var prefer = user_profile.prefer;
switch (prefer) {
case "cis women":
Meteor.call('search.cw', lng, lat, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
return;
} else {
searched = result;
if (searched.length == 0) {
FlashMessages.sendWarning("no more providers found in your area", 3000);
} else {
for (var found of searched) {
var user_profile = Session.get('user_profile');
var right = user_profile.right;
if (!(found._id in right)) {
Template.instance.jades.push(found._id);
}
}
var jadeId = Template.instance.jades.pop();
console.log(jadeId); // returns ofQj98LBQWrSJ8gJs on client
if (jadeId) {
Meteor.call('get.jade', jadeId, (error, result) => {
if (error) {
FlashMessages.sendError(error, 3000);
} else {
Session.set({'jadeId': jadeId});
Session.set({'jade': result});
console.log(result); // returns undefined on client
}
});
} else {
FlashMessages.sendWarning("no more providers found in your area", 3000);
}
}
}
});
break;
case "trans women":
...
methods.js
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
redisCollection.hgetall(jadeId, function(error, object) {
if (error) {
console.log(error);
} else {
console.log(object); // returns { name: 'alex', img: 'null', gender: 'cis woman' } on server
return object;
}
});
},
I solved this by changing the method as follows:
'get.jade': function(jadeId) {
var redisCollection = new Meteor.RedisCollection("redis");
return redisCollection.hgetall(jadeId)
},
I have developed an application, and in this application I want to import file Excel to multiple table in my DB, and since i am a beginner in angularJS and .NET, I work with .net web api and angularjs, and I develop a function, it works when I import the data into a singe table, but the problem how to import the data into 3 table in DB !!! . and the 3 tables are linked to each other (in my exemple code there 2 table Candidature and Candidat). My question is: how to import Excel file to multiple table in DB and thank's. ( i work with asp.net web API and angularJS )
controller.cs:
/////
[Route("api/Candidature/SaveData")]
[HttpPost]
[ResponseType(typeof(Candidat))]
public IHttpActionResult SaveData(List<Candidature> Candidatures, List<Candidat> candidat)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var data in Candidatures)
{
db.Candidature.Add(data);
}
db.SaveChanges();
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
db.SaveChanges();
return StatusCode(HttpStatusCode.OK);
////
service.js:
SaveData: {
method: 'POST' ,
url: serviceBase + 'Candidature/SaveData',
isArray: true,
headers: {
'Content-Type' : 'application/json'
}
},
CandidatureCtrl.js :
$scope.Importation = function (data) {
$scope.SelectedFileForUpload = null;
$scope.UploadFile = function (files) {
$scope.$apply(function () { //I have used $scope.$apply because I will call this function from File input type control which is not supported 2 way binding
$scope.Message = "";
$scope.SelectedFileForUpload = files[0];
})
};
//Parse Excel Data
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
//XLSX from js-xlsx library , which I will add in page view page
var workbook = XLSX.read(e.target.result, { type: 'binary', cellDates:true, cellStyles:true });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (excelData.length > 0) {
//Save data
Candidature.SaveData(excelData).then(function (data) {
if (data.status) {
$scope.Message = excelData.length + " record inserted";
}
else {
$scope.Message = "Failed";
}
}, function (error) {
$scope.Message = "Error";
});
// Candidature.SaveDatacandidature(excelData).then(function (data) {
// if (data.status) {
// $scope.Message = excelData.length + " record inserted";
// }
// else {
// $scope.Message = "Failed";
// }
// }, function (error) {
// $scope.Message = "Error";
// });
// $scope.SaveData(excelData);
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
};
var dialogOpts = {
backdrop: 'static',
keyboard: false,
scope: $scope,
size: 'lg',
templateUrl: 'views/candidature/Importation.html',
controller: ['$scope', '$uibModalInstance','$sce',
function ($scope, $uibModalInstance, $sce) {
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
]
};
$uibModal.open(dialogOpts);
};
Importation.html :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
<script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<!--<script src="app/views/candidature/candidatureCtrl.js"></script>-->
</head>
<body ng-app="agu">
<div ng-controller="candidatureCtrl" class="container" style="margin-top:50px;">
<div class="form-inline">
<input type="file" name="file" class="form-control"
onchange="angular.element(this).scope().UploadFile(this.files)"/>
<input type="button" value="Import" class="btn btn-success" ng-disabled="!SelectedFileForUpload"
ng-click="ParseExcelDataAndSave()" />
<br/>
<span style="color:red">
{{Message}}
</span>
</div>
</div>
</body>
</html>
In your web api, you are expecting two arrays for Candidatures and candidat.
But from your controller you are passing only one array of data excelData.
So when it comes to api it doesn't execute this code,
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
Because candidat is either null or undefined. So it can't go through the loop which the below code is never executed.
db.Candidat.Add(data);
I am using google place SearchBox ( not AutoComplete ) for place search. My objective is I want to restrict the search for a particular country (UK).
I know the same thing can be achieved easily by using AutoComplete. But I can't use this because my map will populate on enter key as well as against a search button.
I am using code to select the first option on search button click.
I have tried with google.maps.LatLngBounds but that only sets the priority of result, not restricting anything.
Html:
<ul class="list-unstyled search-branch">
<li>Search branches:</li>
<li><input type="text" placeholder="City, town or postcode" id="txtbranch" value="Eurochange" />
<input type="button" class="button gold" id="getbranch" value="Search" />
<div style="clear:both;"></div>
<div class="error-message-summary" id="locationnotfound" style="padding: 0;top:-30px; position:relative; font-size:16px;display:none">
No search results found.
</div>
</li>
</ul>
js:
var input = document.getElementById('txtbranch');
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 1512631)
);
var options = {
bounds: defaultBounds
}
var searchBox = new google.maps.places.SearchBox(input, {
bounds: defaultBounds
});
$('#getbranch').click(function () {
var input = document.getElementById('txtbranch');
if (BranchAddressSelector.val() == "") {
return;
}
google.maps.event.trigger(input, 'focus');
google.maps.event.trigger(input, 'keydown', { keyCode: 13 });
return false;
})
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces()[0];
if (typeof (places) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
if (BranchAddressSelector.val() == "") {
return false;
}
var address = places.formatted_address;
if (typeof (address) === "undefined") {
locationNotFoundSelector.css("display", "block");
return false;
}
var latitude = places.geometry.location.lat();
var longitude = places.geometry.location.lng();
$.ajax({
type: "GET",
url: BranchLocatorUrl.GetBranches,
data: { Latitude: latitude, longitude: longitude },
success: function (data) {
if (data.length > 0) {
markers = data;
LoadMap(0, 0);
BranchListSelector.html(CreateSearchHtml(markers));
goToByScroll("dvMap");
BranchListSelector.css("display", "none");
paginationSelector.css("display", "none");
$('.map-distance').css("display", "block");
locationNotFoundSelector.css("display", "none");
var show_per_page = 6;
var number_of_items = BranchListSelector.children('.BranchItem').size();
var number_of_pages = Math.ceil(number_of_items / show_per_page);
totalPages = number_of_pages;
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" style="color: #007ea0;" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while (number_of_pages > current_link) {
navigation_html += '<a class="page_link" style="color: #007ea0;" href="javascript:go_to_page(' + current_link + ')" longdesc="' + current_link + '">' + (current_link + 1) + '</a> ';
current_link++;
}
navigation_html += '<a class="next_link" style="color: #007ea0;" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html).css("float", "right").css("display", "none");
$('#page_navigation .page_link:first').addClass('active_page');
BranchListSelector.children('.BranchItem').css('display', 'none');
BranchListSelector.children('.BranchItem').slice(0, show_per_page).css('display', 'block');
BranchListSelector.css("display", "block");
// paginationSelector.css("display", "block");
$('.map-distance').css("display", "none");
$('#moreBranch').css("display", "block");
}
else {
alert("Data not found.");
}
},
error: function (e) {
alert("Some Problem occurs.Try after some time");
return;
}
});
});
i am trying to show a dynamic data on the ionic slide box with ng-repeat. i am using services to get the data from my sqlite DB but i get nothing. i don't know what to do after 3 days with this issue, here is my code:
template.html
<ion-view>
<ion-nav-title>{{simple.title}}</ion-nav-title>
<ion-content>
<div class="row">
<div class="col col-33 col-offset-33">
<h1 style="font-size: 72px !important;">{{simple.content}}</h1>
</div>
</div>
<div class="row">
<div class="col">
<ion-slide-box show-pager="false" does-continue="true">
<ion-slide ng-repeat="senci in sencillo">
<div class="box">
<h1 style="font-size: 52px !important;">{{senci.sound_title}}</h1>
</div>
</ion-slide>
</ion-slide-box>
</div>
</div>
</ion-content>
</ion-view>
my service.js
angular.module('starter.services', [])
.factory('DBA', function($cordovaSQLite, $q, $ionicPlatform) {
var self = this;
// Handle query's and potential errors
self.query = function (query, parameters) {
parameters = parameters || [];
var q = $q.defer();
$ionicPlatform.ready(function () {
$cordovaSQLite.execute(db, query, parameters)
.then(function (result) {
q.resolve(result);
}, function (error) {
console.warn('I found an error');
console.warn(error);
console.log(error.code + ' / ' + error.message);
q.reject(error);
});
});
return q.promise;
};
// Proces a result set
self.getAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
// Proces a single result
self.getById = function(result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
};
return self;
})
.factory('Sounds', function(DBA) {
var self = this;
self.getSimple = function(simpleId) {
var parameters = [simpleId];
return DBA.query("SELECT * FROM letters WHERE Id = (?)", parameters)
.then(function(result) {
return DBA.getById(result);
});
};
self.getSimpleArr = function(Id) {
var parameters = [Id];
return DBA.query("SELECT * FROM words WHERE letter_id = (?)", parameters)
.then(function(result) {
return DBA.getById(result);
});
};
return self;
});
controller.js
.controller('SoundsSimpleCtrl', function($scope, Sounds, $stateParams, $ionicSlideBoxDelegate) {
$scope.sencillo = [];
$scope.getSimple = function($stateParams) {
Sounds.getSimple($stateParams.simpleId).then(function(single){
$scope.simple = single;
$scope.getArrSimple($scope);
});
};
$scope.getArrSimple = function($scope){
Sounds.getSimpleArr($scope.simple.Id).then(function(detalle){
$scope.sencillo = detalle;
$ionicSlideBoxDelegate.update();
});
};
$scope.getSimple($stateParams);
});
i hope you guys can help me, regards.
Hi people i resolved my problem, i had a bad SQl Request, im so sorry for be annoying, i just changed to use my service function from getById() to getAll() (these functions are being taken from DBA Factory) like this:
self.getSimpleArr = function(value) {
var parameters = [value];
return DBA.query("SELECT * FROM words WHERE letter_id = (?)",parameters)
.then(function(result){
return DBA.getAll(result);
});
};
the getById() function was returning only the first row of the request, absolutely MY BAD. Regards
I need to know about to increment helper variable count in meteor.
For example :
<head>
<title>hello</title>
</head>
<body>
<h1>Welcome to Meteor!</h1>
{{> hello}}
</body>
<template name="hello">
<button>Click Me</button>
{{#each arr}}
{{counter}} <!-- How to get the foo index here? --> {{name}}
{{/each}}
</template>
Js Code :
if (Meteor.isClient) {
// counter starts at 0
Template.hello.helpers({
counter: function () {
return Session.get('counter');
}
});
Template.hello.helpers({
arr: function () {
console.log(Session.get('arrres'));
return Session.get('arrres');
}
});
Template.hello.events({
'click button': function () {
Session.set('counter', 0);
Meteor.call('arrfun',10, function (error, res) {
if (!error)
{ arrres = res;
Session.set('arrres', arrres);
console.log(res);
}
else{}
} );
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
Meteor.methods({
arrfun:function arrfun(properties, callback)
{
var obj = [];
for(var i = 0 ; i < 10; i++)
{
var obj1 = new Object();
obj1.name = 'abc'+i;
obj.push(obj1);
}
return obj;
}
});
});
}
The above 'arr' contains list of names that present in object.Now can iterate 'arr' it will comes names.
now can we print names as like 1 abc
2 xyz until 'arr' completed.
So how can we print numbers from 1 to 'arr' length before names.
So please suggest me what to do for this.
It's a little hard to interpret your question but I think you want this:
Template.hello.events({
'click button': function(event) {
Session.set('counter', Math.round(Math.random() * 10));
}
});
Template.hello.helpers({
'arr': function() {
var counter = Session.get('counter');
var arr = [];
for(var i = 0; i < counter; i++) {
arr.push(i + 1);
}
return arr;
}
});
And in your hello template:
<ul>
{{#each arr}}
<li>{{this}}</li>
{{/each}}
</ul>
This will generate a random number between 0-10 every time you click the button, and then the template will count up to this random number in sequence.