Using Jaydata, I can populate my simple local database from an odata service. The database has an Organization table.
I am also using AngularJs. The following code gets the organizations from the local database and binds them to $scope.Organizations which is referenced on my OrganziationIndex view. I've tested this so far in Chrome, Safari on iOS7, and the Android browser built in to ICS, and it works as expected in each of those browsers.
var localDB = new InspecTechDB({
name: 'local',
databaseName: 'InspecTech'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
$.when(localDB.onReady())
.then(function () {
$scope.inspectechdb = localDB;
$scope.organizations = localDB.Organizations.toLiveArray();
$scope.message = "Organizations fetched from local store. Click one of them!";
});
});
However, in IE11, I get an error message on the console that states simply "Pure Class" on this line and the organizations are not listed on the view:
scope.organizations = localDB.Organizations.toLiveArray();
A Google search reveals literally no results: Google Search
I've verified with console logging that the table is populated from the odata service. What I have found is that if I change the code as shown below (changed from local database to odata service), that the error goes away:
var remoteDB = new InspecTechDB({
name: 'oData',
oDataServiceHost: '/odata'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
$.when(remoteDB.onReady())
.then(function () {
$scope.inspectechdb = remoteDB;
$scope.organizations = remoteDB.Organizations.toLiveArray();
$scope.message = "Organizations fetched from local store. Click one of them!";
});
});
I do intend for the application to be run offline so I need to be able to get the organizations from the local database and not the odata service.
Can someone point in the right direction for what I need to do to make this work in IE?
Thanks,
Mike
UPDATE 1:
I'm observing the same error in Firefox.
UPDATE 2:
I'm observing the same error in Chrome if I change the provider like so:
var localDB = new InspecTechDB({
name: 'indexedDb',
databaseName: 'InspecTech'
});
So the problem is not specific to IE, more like specific to the IndexedDB provider.
UDPATE 3:
Here's some workaround code. I'd still like to know about the problem with .toLiveArray().
var localDB = new InspecTechDB({
name: 'local',
databaseName: 'InspecTech'
});
app.controller('OrganizationIndex', function ($scope, $data) {
$scope.organizations = [];
//wait until the localDB is ready, then get the Organizations
//$.when(localDB.onReady())
//.then(function () {
// $scope.inspectechdb = localDB;
// $scope.organizations = localDB.Organizations.toLiveArray()
// .then(function () {
// $scope.message = "Organizations fetched from local store. Click one of them!";
// });
//});
//this code replaces the above code since I can't make toLiveArray work w/ indexedDB provider
$.when(localDB.onReady())
.then(function () {
var organizations = localDB.Organizations.toArray();
return $.when(organizations)
.then(function (orgs) {
$scope.$apply(function () {
orgs.forEach(function (organization) {
$scope.organizations.push(organization);
});
});
});
});
});
Related
I have a SQL Server database and an Asp.net web api for my web service.
I have below UI for adding a category
I have below UI for adding a expense in that category
After I login into the application.
Category:
I am creating a category which is getting created and in the database there is a record. Refreshing the page it displays the category. After logging out and logging in again the category is not displayed here.
Expense :
When I create a new expense, it is not displayed at all. But the created category is taken into the drop down but not displayed as in the screenshot above.
Code as below
Inserting my expense
$scope.insertExpense = function () {
var ExpenseObj = {
"AmountSpent": $scope.amountspent,
"DateofExpense": $scope.datevalue,
"UserID": $rootScope.id,
"CategoryID": $scope.selectedcategory.Id
};
appResources.expenseResource.save(ExpenseObj, function () {
alert("Expense Added");
});
}
I retrieve my category using
appResources.categoryResource.query(function (data) {
$scope.Categories = data;
console.log(data);
});
I retrieve my category using
appResources.expenseResource.query(function (data) {
$scope.Expenses = data;
console.log(data);
});
AppResources has only the webapi calling mechanism as
expenseManager.factory('appResources', function ($resource) {
var baseURL = "http://localhost:8080"
var registerResource = $resource(baseURL+'/api/Register/:id');
var categoryResource = $resource(baseURL + '/api/Category/:id');
var expenseResource = $resource(baseURL + '/api/Expense/:id');
return {
registerResource: registerResource,
categoryResource: categoryResource,
expenseResource: expenseResource
}
});
I am currently trying to create a remote method in loopback that will query a firebase database using the Firebase Admin SDK in NodeJS.
It works, but the issue I am having is that I am unable to make it realtime. It keeps crashing with an error pointing to the callback function being called more than once.
Here is a snippet of the code for my remote method:
'use strict';
module.exports = function(Scusers) {
var admin = require("firebase-admin");
Scusers.listItems = function(cb) {
// Get a database reference
var db = admin.database();
var ref = db.ref("users");
// Attach an asynchronous callback to read the data at our posts reference
var items = [];
// return list of users ordered by key and push each object into an array
ref.orderByKey().on("value", function(snapshot) {
snapshot.forEach(function(data) {
items.push(data.val());
});
// return array
cb(null, items);
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
};
}
If I change this line:
ref.orderByKey().on
for:
ref.orderByKey().once
It works, but on my front-end which is coded in AngularJS, it won't see the changes unless I manually call a refresh.
What should be the best approach to this? Sorry if it is unclear or my approach is wrong, I am so new at this. Thanks!
I am trying to get the metadata before I perform any queries on the page, because each query is trying to get the metadata for a total of 5 times and the page is very slow. I am hoping this helps.
//version info:
var breeze = {
version: "1.5.4",
metadataVersion: "1.0.5"
};
Howevever I am getting this error:
manager.fetchMetadata(...).then(...).fail is not a function
Here is the code sample:
var manager = emProvider.createManager();
function getMetaData()
{
var deferred = $q.defer();
manager.fetchMetadata()
.then(function (data, status) {
deferred.resolve(data);
console.log('manager.fetchMetadata() success');
})
.fail(function (data, status) {
deferred.reject(data);
console.log('manager.fetchMetadata() reject');
});
return deferred.promise;
}
THis is what the createManager function looks like from the injected 'emProvider' service.
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
// private function to create a new manager
function createManager() {
var manager = masterManager.createEmptyCopy(); // same configuration; no entities in cache.
// ... copy in some entities (e.g.,picklists) from masterManager
return manager;
}
try the following... surround all of your code blocks with anonymous self-invoking functions except for the master manager creation, comment out the getMetaData function, be sure to pick up the right adapter for your service... breeze odata configuration , make sure Q is on your js bundle at the top of your page.
breeze.config.initializeAdapterInstance("dataService", "odata");
var masterManager = new breeze.EntityManager(serviceRoot + 'odata/');
(function () {
var op = breeze.FilterQueryOp;
var query = null;
query = new breeze.EntityQuery()...
...all of your other breeze code...
masterManager.executeQuery(query).then(function (data) {...
})();
If you are using $q from AngularJS, you should use .catch instead of .fail. AngularJS uses .catch for errors in promises.
i am fresher at nodejs and socket.io. i am trying to made a chat application using nodejs, socket.io and angularjs in express framework. i am lacking basic idea how chat is performed privately.up to this stage my code works chatting in a group of connected users. here is my server code
var server = require('http').Server(app);
var io = require('socket.io')(server);
var socket = require('./routes/socket.js');
server.listen(8000);
console.log('server listening on port:8000');
io.on('connection',socket);
and my main socket file consit code like:
module.exports = function(socket){
console.log('connected'+' '+'socketId :'+socket.id);
//console.log(req.session.id);
var users =[];
socket.emit(socket.id);
socket.on('username',function(data){
users.push({id:socket.id,message:data.username});
socket.emit('username', users)
})
socket.on('typing',function(data){
//socket.emit('typing',{message:"helo angular"});
socket.broadcast.emit('typing',{message:data.message});
});
socket.on('typing-stop',function(data){
//socket.emit('typing',{message:"helo angular"});
debugger;
socket.broadcast.emit('typing-stop',{message:data.message});
});
socket.on('new-user',function(data){
socket.emit('new-user',data);
socket.broadcast.emit('new-user',data);
})
socket.on('message',function(data){
users.push({message:data.message});
socket.emit('message',{id:socket.id,message:data.message});
socket.broadcast.emit('message',{id:socket.id,message:data.message});// emit the message to every one connected in server
})
socket.on('disconnect',function(){
console.log('user disconnected');
socket.broadcast.emit('disconnected',{'message':'user left the chat room'});
});
}
i am abe to load all the users who get logged in my app.
all i want is to click to the available and start private messaging, till now chat is public everyone connected in server can see message.
my angularjs controller code goes like:
function orgController(notifyService, chatSocket, $state,$http) {
chatSocket.connect();
var vm = this;
vm.sendMessage = sendMessage;
vm.messages = [];
vm.users = [];
var id = $state.params.id;
$http.get('/users/' + id).then(function(result) {
console.log(result.data);
vm.userData = result.data;
chatSocket.emit('new-user', { 'username': result.data.details.firstName + ' ' + result.data.details.lastName });
});
chatSocket.on('new-user',function(data){
vm.users.push(data);
})
function sendMessage(msg) {
//console.log(msg);
if (msg != null && msg != '') {
chatSocket.emit('message', { message: msg });
vm.msg = '';
} else {
vm.msg = '';
}
}
chatSocket.on('message', function(data) {
//debugger;
console.log(data);
vm.messages.push(data);
});
}
NOTE: i have included angular-socket.io modules and inject its dependency in a service called chatSocket which only return socketFactory.
now i want to click in a user from logged in userlist and start communication. how can i do it from (socket.id). which socket generates or from session id? anyone has better way of doing such. any suggestion and response are highly appreciated.
Basically what you need to do is emit an event to a specific socket like this.
io.to(socket.id).emit('privateMessage', {message: <message goes here>});
then on the client side
socket.on('privateMessage', function(data){
var message = data.message;
//do stuff, display message etc...
});
I am learning about the MEAN stack, and have created a REST API which posts a review to a collection in MongoDB.
I have defined a service as given:
angular.module('myApp')
.constant('baseURL', 'http://localhost:8080/');
angular.module('myApp')
.service('addReviews', ['$resource', 'baseURL', function($resource, baseURL) {
this.getReviews = function() {
return $resource(baseURL+'reviews/', null, {'save': {method: 'POST'}});
};
}]);
Now, I am calling this service from my controller:
angular.module('myApp', ['ngResource'])
.controller('reviewController', ['$scope', 'addReviews', function($scope, addReviews) {
$scope.reviewSubmit = function() {
$scope.receivedReviews = false;
var review = {
// some data
};
$scope.reviews = addReviews.getReviews().query(
function(response) {
$scope.reviews = response;
$scope.receivedReviews = true;
},
function(response) {
$scope.reviews = response;
// print error message
}
);
console.log($scope.reviews); // showing empty array
};
}]);
In routes.js, I have configured my route as:
var Reviews = require('./models/reviews');
...
app.post('/reviews', function(req, res) {
Reviews.create(req.body, function(err, post) {
if (err) {
return res.send(err);
}
return res.json(post);
});
});
I am trying to post a new review to the Reviews collection. However, $scope.reviews is showing an empty array. I logged the requests, and it shows a GET request is being to /reviews instead of POST. I think I should use save() instead of query(), but I have seen some tutorials online where they used query() despite the method being PUT/POST in the service. I am really confused. Can anyone point out how I can post the data (in var review) to the Reviews collection?
There are some issues with your code on the angular side of things.
You want to use $resource as an all-purpose object to communicate with the API. It has built-in functionality to:
query: get all resources from a given API endpoint
get: a single resource, usually by specifying that resource's id
save: post, with an object sent across in the body of the request. NOTE: you don't need the {'save': {method: 'POST'}} in your $resource configuration, you get it for free.
remove and delete: self-explanatory
So you'd want to set up your reviews factory (incl. url constant) like:
angular.module('myApp', ['ngResource'])
.constant('baseURL', 'http://localhost:8080/')
.factory('Reviews', ['$resource', 'baseURL', function($resource, baseURL) {
return $resource(baseURL+'reviews/:id', {id: '#id'});
}]);
If you want to have access to all saved reviews in your controller, as $scope.reviews, you'd do something like:
angular.module('myApp')
.controller('reviewController', ['$scope', 'Reviews', function($scope, Reviews) {
// hit API endpoint to get all reviews
// will have to have app.get('/reviews', function(req, res) {...})
// configured in your node code
Reviews.query(function(data) {
$scope.reviews = data;
}, function(error) {
console.log(error);
});
// and if you want to take a user-written review, say $scope.userReview,
// from the view and save it to the database on click function submitReview()...
$scope.userReview = {
message: '',
createdTime: null
};
// ^ not sure what your ReviewSchema looks like on the backend, but for example...
$scope.submitReview = function() {
if ($scope.userReview.message.length) {
$scope.userReview.createdTime = Date.now();
Reviews.save($scope.userReview);
// ^ this will make POST request with the $scope.userReview object as the request body
}
};
}]);
The create method on your back end looks fine. The object (or maybe just string) you send across will have to match your review schema. You may want to log the request body to make sure you're getting what you expect.
Have a look at this short post on using $resource to interact with RESTful APIs, and (the slightly more confusing) angular $resource docs, for more information on the $resource service.
Hope this helps you!