Angular JS Select option from database not working - angularjs

I have a select option list in Angular.js. I populate list from sql server database. It's working fine. But when I want to display data back from sql server, it doesn't work.
to populate from database (its populated)
<select ng-model="roomno" ng-options="r.Room_Name for r in rooms" value= "{{roomno}}"></select>
Now I want to show 1 particular item in that list, which is stored in database.
I tried with
$scope.roomno = response.data[0].Room_Name;
It's not working.

I would like to suggest You to use code like this:
$scope.roomno = response.data[0].Room_Name.toString();
this works fine. because somewhere stores as integer and somewhere string so need to convert as string.

How are you connecting to the server? Presumably you are using HTTP get? In which case if you want one particular room then you might want to call a separate request using the id?:
var _getRoom = function (roomId) {
return $http.get('api/Rooms/' + roomId).then(function (response) {
if (typeof response.data === 'object') {
_room = response.data;
return response.data;
} else {
return $q.reject(response.data);
}
}, function (response) {
return $q.reject(response.data);
});
};

Related

kinvey fetching and remove not working (AngularJS)

I have this problem with kinvey backend,
I'm trying to fetch data from my collection but it doesn't work for me. here is my code :
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
Can you help me please
If you let run the code you have posted then consider four things:
Make sure you have Kinvey implemented:
<script src="https://da189i1jfloii.cloudfront.net/js/kinvey-html5-sdk-3.10.2.min.js"></script>
Make sure you have initialized the Kinvey service before:
// Values shown in your Kinvey console
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
Make sure you are logged in with a user that has the rights to read your collection (should be fine using the All Users role (default)):
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
})
.catch(function(error) {
console.log (error);
});
Output the return result to see whats coming back. To make sure you do the query AFTER successful login, paste you query inside the .then function of login.
I'm not sure if your query is valid unter 3.x since a lot has changed and I'm not working with older Kinvey versions.
So that all together would look like this:
// Initialize Kinvey
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
// Login with already registered user
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
// Your query
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// Output of returning result
console.log (entity);
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
})
.catch(function(error) {
console.log (error);
});
There are now three return sets possible:
Nothing (as you say) -> Something missing/wrong in the code (compare yours with mine)
Empty array: Your query didn't find anything, adapt the search value(s)
One or more entries in the array -> All fine, what you were looking for!
Hope that helps!
When querying by _id there is a built in method: http://devcenter.kinvey.com/angular/guides/datastore#FetchingbyId
Try switching to var stream = dataStore.findById('entity-id');
Also check to make sure you don't have any preFetch or postFetch BL that is interfering with the query.

How do I query a database with AngularJS's $resource factory for a specific set of rows?

I'm building an app using AngularJS and the MEAN Stack, and was wondering if it was possible to use the $resource factory to query a MongoDB database for a set of rows that have a certain value in one of their columns.
For example, if I wanted to build a Todo app, and I had a table with a column containing a persons username and a column with a string that had a reminder, is it possible to query the database for all the rows that have a particular username in the username column? Or, do I have to do something like this:
Todo.service.ts:
export function TodoResource($resource) {
'ngInject';
return $resource('/api/todo/:query', {
id: '#_id'
query: '';
});
}
app.js
var list = [];
this.Todo.query().$promise.then( (data) => {
for(let datum of data){
if(datum.userName == email){
list.push(datum);
}
}
});
In this sample case, I'm not really querying the database, just getting the entire table and filtering the results by myself. Is this the only way to do it, or can I directly query the database?
If you are using NODE and MongoDB, then you must be using Mongoose.
For this purpose its better to filter data on server not on client, as it would
- Decrease the amount of data on network
- Prevent unwanted data to be sent to client
Also, If you dont want to manually filter the data on server with a function, there is a function in mongoose
var query = collection.find({_id: '001'});
query.exec(function (err, results) {
if (err) {
res.json(err);
}
if (results) {
res.json(results);
}
});
this will add filter in query to mongodb before executing it, and will fetch only records having
id= 001;
i.e. filtered data
By this you will not have to filter data manually, MongoDB will handle it all.
You can send the id in the request URL
localhost:8080/collectionName/001
on NODE server:
function (req, res) {
var mainUrl = req.url.split("/");
if (mainUrl.length > 2) {
query = collection.find({_id: mainUrl[2]});
} else {
query = collection.find();
}
query.exec(function (err, results) {
if (err) {
res.json(err);
}
if (results) {
res.json(results);
}
});
}
You can also make your url like:
localhost:8080/collectionName?id='001'
then on server:
var url_parts = url.parse(req.url, true);
var queryFactors = url_parts.query;
var id= JSON.parse(queryFactors["id"]);
and use above code again for queering.
Hope this helps.

React and Meteor Subscription

I am not sure if this is a limitation to React and Meteors connection as documentation suggests that it should be possible without the extra parameter.
When I call a meteor subscription in react if I do not explicitly state the parameter in the query it returns any data, ignoring the specified data in the publish function.
Meteor.publish("supplier", function() {
if(this.userId) {
var user = Meteor.users.findOne(this.userId, { fields : { active : 1 }});
if(user.active != this.userId || user.active != undefined){
// This only returns 1 singular supplier - is correct
var supplier = Supplier.find({ _id : user.active, users : this.userId });
return supplier;
} else {
return this.ready();
}
} else {
return this.ready();
}
});
Now I call the subscription in react as so
getMeteorData: function () {
var data = {}
handle = Meteor.subscribe("supplier");
if(handle.ready()) {
data.supplier = Supplier.findOne(); // Returns Wrong supplier
//data.supplier = Supplier.findOne({_id: session.get("active")}) // Returns correct supplier
data.supplierReady = true
}
return data;
},
This returns the first supplier in the collection not the one logged in the publish function on the server! However if I explicably pass { _id : user.active} it works!
Now it was my understanding that by doing the logic on the server within the publish function that I could simply use Supplier.findOne() but this is not the case and I don't understand why. Is this a limitation on React/Meteor or am I implementing this wrong?
This isn't a React-specific issue, it's a result of the way findOne works. If you have one or more documents in your client side Supplier collection, Supplier.findOne() will just grab the first record available without reference to the document(s) you just fetched from your subscription.
This means either (a) you have more than one supplier available on the client side due to other preexisting subscriptions, or (b) you are returning more than one supplier from the handle subscription.
Check the state of the client side collection prior to the handle subscription. If there's 1 or more docs and that is the intended state of your application, then modify the client side findOne to add {_id: user.active} as you have before.

SQLite query result not returned from function

What I'm trying to do is create a kind of a storageservice in which I use a SQLite database to store key and value pairs after which I can retrieve them based on the key. To achieve this I set up the following code:
.service('StorageService', function($cordovaSQLite, $q) {
if(window.cordova) {
db = $cordovaSQLite.openDB("vouchers.db");
} else {
db = window.openDatabase("vouchers.db", "1.0", "Vouchers db", -1);
}
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS vouchers (key text, value text)");
return {
getItem: function(item) {
var query = "SELECT key, value FROM vouchers WHERE key = ?";
$cordovaSQLite.execute(db,query,[item]).then(function(result) {
console.log(result.rows[0].value);
return result.rows[0].value;
});
},
setItem: function(item, data) {
var query = "INSERT INTO vouchers (key, value) VALUES (?,?)";
return $cordovaSQLite.execute(db, query, [item, data]);
}
};
})
Now, most of this stuff is working great. I can store items in the db and even retrieve and log them from inside the function as you can see on the following line:
console.log(result.rows[0].value);
When I log this I get the expected value, but when I return it and log it in the controller where I'm using this service it's remaining undefined. The code in my controller looks as follows:
var test = StorageService.getItem("testje");
console.log(test);
Please note that there are NO console errors. Just two logs. One from the controller that is undefined, and one from the service that returns the value as intended:
controllers.js:465 undefined
services.js:122 dit is een testje!
I was hoping anyone can tell what is going wrong here. If there's any info or code that can be helpful and I left out, let me know.
That's because your getItem: function(item) { uses a promise to retrieve the results.
Try to change your code to this instead:
getItem: function(item) {
var query = "SELECT key, value FROM vouchers WHERE key = ?";
return $cordovaSQLite.execute(db,query,[item]);
});
and call your service this way:
StorageService.getItem("testje").then(function(result){
console.log(result);
});
You'll be able to view the results then.
I suggest you to study some basic principles of promises: you'll encounter them very often if you use $http get and post requests and any other async stuff in javascript.

Saving and Getting Data / Rows to and from PouchDB

i am very new to pouchdb, meaning i have not yet been successfully able to implement an app that uses it.
This is my issue now, in my controller i have two functions:
var init = function() {
vm.getInvoicesRemote(); // Get Data from server and update pouchDB
vm.getInvoicesLocal(); // Get Data from pouchDB and load in view
}
init();
Basically in my app i have a view that shows customer invoices, now i want customers to be able to still see those invoices when they're offline. I have seen several examples of pouchdb and couchdb but all use the "todo" example which does not really give much information.
Now i'm just confused about what the point was in me spending hours understanding couchdb and installing it if in the end i'm just going to be retrieving the data from my server using my API.
Also when the data is returned how does pouchdb identify which records are new and which records are old when appending.
well, i m working on same kind..!this is how i m making it work..!
$scope.Lists = function () {
if(!$rootScope.connectionFlag){
OfflineService.getLocalOrdersList(function (localList) {
if(localList.length > 0) {
$scope.List = localList;
}
});
}else{
if(!$scope.user){
}else {
Common.callAPI("post", '***/*************', $scope.listParams, function (data) {
if (data !== null) {
$scope.List = data.result;
OfflineService.bulkOrdersAdd_updateLocalDB($scope.List);
}
});
}
}
};
so,$scope.List will be filled if online as well as offline based on connectionFlag
note : OfflineService and Common are services.
call method:
$ionicPlatform.ready(function () {
OfflineService.configDbsCallback(function(res) {
if(res) {
$scope.Lists();
}
});
});
u can try calling $scope.Lists(); directly..!
hope this helps u..!

Resources