I'm still trying to get my head around the whole publish/subscribe aspect of Meteor.
This is the gist of what I'm trying to achieve.
On server side, at "Meteor.startup", I grab RSS feeds from a blog. This part works. Basically, my server code looks like
Items = new Meteor.Collection "items"
Meteor.startup ->
..
.. # code for fetching the RSS feeds
..
for each feed
Items.insert
title:item.title
console.log Items.find().count() # this returns the correct count
Meteor.publish "items", ->
Items.find()
Now that I have published the "items", I want to subscribe to it from the client.
Items = new Meteor.Collection "items"
Meteor.subscribe("items")
console.log Items.find().count()
But above gives me "0".
What am I doing wrong?
Subsribing is asynchronous, you need to wait for the subscription to be completed by passing a callback function before trying to access the data in the collection. Example in Javascript:
Meteor.subscribe('items', function () {
console.log(Items.find().count());
});
Related
I have been trying to retrieve data from mongodb (i'm using also mongoose) and send it to angular to fill the ng-repeat list with data. I am able to print data on blank page from mongo OR display data in list if i declare exemplary static array with data in a list on webpage but i dont know how to connect it to work with data from mongo. I am new to MEAN stack so please spare me.
Please go through video tutorial of Bucky Robert. Try to create the project from Hello world then you will understand.
Node JS tutorial click here
MEAN STACK tutorial: click here
First Create RestFul API using Node js
http://adrianmejia.com/blog/2014/10/01/creating-a-restful-api-tutorial-with-nodejs-and-mongodb/
Then consume the same using following example.
MessageServiceData.getMessageService=function(){
var def = $q.defer();
$http.post("www.url.com", data)
.success(function(messages){
def.resolve(messages);
})
.error(function(messagesFail){
console.log('error:'+JSON.stringify(messagesFail));
def.reject([{"Error":JSON.stringify(messagesFail)}]);
});
return def.promise;
}
I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.
I'm having an issue getting Ember.js with Ember Data to hit a nested resource API endpoint. Here is my code:
https://gist.github.com/feliksg/7470254
Here is what i'm using:
DEBUG: ------------------------------- ember.js:3224
DEBUG: Ember : 1.2.0-beta.3 ember.js:3224
DEBUG: Ember Data : 1.0.0-beta.2 ember.js:3224
DEBUG: Handlebars : 1.0.0 ember.js:3224
DEBUG: jQuery : 2.0.3 ember.js:3224
DEBUG: -------------------------------
I'm also using Ember Appkit as the base for this project.
Basically the issue is when I try to submit a new post, ember data does the following:
POST request to /user/posts
instead of a
POST request to /users/1/posts
In addition, for some reason the request payload as shown by chrome inspector shows the form data being passed to the API looks like this:
{ "user/post": { "published":false, "created_at":null, "user":"1" } }
However, I would expect the data to be passed in like this:
{"post": { "body":"some text...", "published":false, "created_at":null, "user_id":"1" } }
So for some reason, it doesn't even pass in the 'body' field even though I have it in the form.
Any help is greatly appreciated!
UPDATE 1
When I visit http://localhost:8000/#/users/1/posts, it sends a GET API request to /users.json. There must be something wrong with the way I set up the PostsRoute but i'm not sure how to fix it.
UPDATE 2
I've updated my PostsRoute to fetch the JSON without using Ember Data which returns the records, but now the posts template does not render. My PostsRoute now looks like this:
PostsRoute = Ember.Route.extend
model: (params) ->
user = #modelFor('user')
userId = user.get('id')
return $.getJSON('http://localhost:5000/api/v1/users/' + userId + '/posts.json')
I also get the following error:
Error while loading route: TypeError: Object # has no method 'slice'
So when you create/use 'users/post' you are defining a namespace where the post lives, not that it's underneath a specific model. AKA, it isn't going to use the associated user model to build up your url, it's just going to make requests using users as part of the post.
I'm not totally positive why the body isn't being attached to the post, are you sure the model includes the body? Are you sure the body property exists on the model you are sending into the createRecord?
BTW, needs doesn't do anything on a route, it only applies to controllers.
I'm following a knockout.js tutorial for loading data from the server and I'm a bit confused on where the query is actually coming from. The tutorial can be found here and the specific bit of code I'm talking about is on page 2.
I understand the necessity for using ajax, but I'm not actually sure how to make a query based on what they're doing.
$.getJSON("query/tasks", function(allData) {
var mappedTasks = $.map(allData, function(item) { return new Task(item) });
self.tasks(mappedTasks);
});
The description of what is taking place:
On this server, there's some code that handles requests to the URL /tasks, and
responds with JSON data. Add code to the end of TaskListViewModel to request that
data and use it to populate the tasks array:
So, say I'm working with PHP and want to make the following query to find the tasks:
$tasks= mysql_query("select * from tasks");
Where would I place this query? I see it's somehow related to /tasks, but what's going on here exactly?
edit, would I do something like this? So essentially the $.getJSON request is calling a function residing at query/tasks in this case?
//assuming this is on query.php
Class query{
function tasks(){
$task = mysql_query("select * from tasks");
return $task;
}
}
Essentially what is happening is that you are making an AJAX call to some endpoint on your server that will return JSON data. I haven't worked with PHP in quite a while, but you are basically requesting a resource on your server. Let's say that your website is http://www.myawesomesite.com. If you were to make an AJAX request to "/tasks", there will be a request to http://www.myawesomesite.com/tasks that is expected to return JSON data.
That resource can be another page, a web-service of some kind, whatever you have available. I work primarily in the ASP.NET MVC space, so my experience is different from PHP, but the idea is the same. You are making a request to a resource on your server to return JSON data. Whatever that resource is is up to you. HTH!
Here is a collection I define in backbone.js
var List=Backbone.Collection.extend({
model: Item,
url: "TodoApp/index.php/todo"
});
var list=new List
Then I created a Model in the collection with an ID=80
Now, when I do list.fetch();
It will make a call to
"TodoApp/index.php/todo/80"
However, at the backend, using Codeigniter, I really need to have
TodoApp/index.php/todo/get/82.........where get is a function I defined to access DB
So, should I change the Collection url to "TodoApp/index.php/todo/get"
But again, that's not really where the resource is located?
In route.php try:
$route['todo/(:num)'] = "todo/get/$1";
HERE is what I ended up doing.
I renamed the index of the controller to resource
therefore using a URL of:
TodoApp/index.php/todo/resource
When getting a GET request at
TodoApp/index.php/todo/resource/80
extract the second segment of the URI and read from DB with that.