I use Angular 6 and smart table :
https://akveo.github.io/ng2-smart-table/#/.
Everything works just fine, till I try to change data from static to dynamic :
This works and shows everything in table :
source: LocalDataSource = new LocalDataSource();
data = [{
id: 1,
Customer: 'UK LTD',
Name: 'Mark Poll',
Code: '84615A',
PostalCode: 'U48K46',
Date: '09/19/2018',
},
];
this.source.load(this.data);
and this doesnt :
data1 = [];
source: LocalDataSource = new LocalDataSource();
getArray() {
this.afDatabase.list('/imones').valueChanges().subscribe(res => {
this.data1 = res;
console.log(this.data1)
})
}
this.source.load(this.data1);
Outputs are equal :
What's wrong with that and maybe somebody was facing this problem ?
I did not work with Firebase or ng2-smart-table before, but it should work if you move your loading of the data-source within the subscribe.
source: LocalDataSource = new LocalDataSource();
getArray() {
this.afDatabase.list('/imones').valueChanges().subscribe(res => {
this.source.load(res);
})
}
Related
I am using a ColumnSet and the helper.insert function for a multi row insert.
I have a table column where I want to use the Postgres Date/Time now() function.
const cs = new helpers.ColumnSet([
'lastname',
{
name: 'rental_date',
def: 'now()'
}
], { table: { table: 'book_rental', schema: 'public' } })
let rentals = [
{
lastname: 'Mueller'
},
{
lastname: 'Johnson'
}
]
let insert = helpers.insert(rentals, cs)
db.result(insert)
.then(data => res.json({ message: 'Ok!' }))
.catch(err => res.json({ message: 'Not ok!' }))
It seems to be working by using def: 'now()', but I want to make sure that I am using it the right way.
Edit:
Regarding the answer in the comment. I tried to do the insert manually and it looks like Postgres is converting the 'now()' string into the now() function.
INSERT INTO book_rental (lastname, rental_date) VALUES ('Mueller', 'now()');
To involve your answer, am I right that this should be the correct code then?
const cs = new helpers.ColumnSet([
'lastname',
{
name: 'rental_date',
mod: ':raw',
def: 'now()'
}
], { table: { table: 'book_rental', schema: 'public' } })
Your code doesn't look right, for the following reasons:
You want to use now() without any condition, but the def value is only used when the property doesn't exist in the source object (see Column). The init callback is what should be used instead to guarantee the right value override.
You return now() as an escaped string, while the query needs it as a raw-text string.
First, let's declare a reusable Raw Text string, as per Custom Type Formatting:
const rawText = text => ({toPostgres: () => text, rawType: true});
Then you can define the column like this:
{
name: 'rental_date',
init: () => rawText('now()')
}
And make sure you are using the latest version of pg-promise (v7.2.1 as of this writing).
Or alternatively, you can declare it like this:
{
name: 'rental_date',
mod: ':raw', // same as mode: '^'
init: () => 'now()'
}
This syntax however will work in all versions of the library, and perhaps is even simpler to use ;)
There is a list of news article in a page. Everytime user clicks on it, it saves news id and title to localstorage. My code is replacing localstorage data everytime I click new item.
How do I append new data into localStorage ?
Setting localStorage
awardForArticleRead: function(latestNews){
var articleData = {};
articleData['newsId'] = latestNews.news_id;
articleData['newsTitle'] = latestNews.title;
localStorage.setItem("articleRead", JSON.stringify(articleData));
},
calling function while it goes to detail page
newsDetail: function(key, id) {
var _this=this;
newsDetail = API_DATA['getLatestNews'][key];
myApp.mainView.loadPage('news1.html');
myApp.onPageInit("news_detail", function(page){
_this.awardForArticleRead(newsDetail);
_this.showNewsDetails(newsDetail);
})
},
You need to read the old data, convert to object (JSON.parse), add the new data, then write the amended data to localStorage
awardForArticleRead: function(latestNews){
var store = JSON.parse(localStorage.getItem("articleRead") || '[]');
store.push({
newsId: latestNews.news_id,
newsTitle: latestNews.title
});
localStorage.setItem("articleRead", JSON.stringify(store));
},
this would result in an array of items, like:
[{
newsId: 1,
newsTitle: 'title 1'
}, {
newsId: 2,
newsTitle: 'title 2'
}, {
newsId: 3,
newsTitle: 'title 3'
}]
so other code that reads the localStorage would have to be changed appropriately
Alternatively:
awardForArticleRead: function(latestNews){
var store = JSON.parse(localStorage.getItem("articleRead") || '{}');
store[latestNews.news_id] = latestNews.title;
localStorage.setItem("articleRead", JSON.stringify(store));
}
would result in the data being:
{
1: 'title1',
2: 'title2',
3: 'title3',
}
where 1,2,3 are the news_id's
As you have not shown how the localStorage data is used (read) then I can't really say which is the better option for you
There is no set add or append function, however you can simply gather the old data, combine them in the code and replace the new data into local storage.
Something like this:
function addToLocalStorage(nameOfItem, newData){
var oldData = localStorage.getItem(nameOfItem);
if(oldData !== null) {
localStorage.setItem(nameOfItem, oldData + newData);
} else {
localStorage.setItem(nameOfItem, newData);
}
}
I am working with nodejs and using module named "JSONAPI-Serializer" for serialization and deserialization purpose.
I am able to serialize the objects without any issue but not able to deserialize the same serialized data.
So,using below code I am able to serialize the data:
root#test$: node test.js
var data = [{ id: 1},{ id: 2 }];
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
var UserSerializer = new JSONAPISerializer('id', {"test":"me"});
var users = UserSerializer.serialize(data);
console.log("Serialized:\n", UserSerializer.serialize(data));
Below is the generated result for the same:-
Serialized:
{ data: [ { type: 'ids', id: '1' }, { type: 'ids', id: '2' } ] }
But on deserialization, I am not able to make it work trying to perform the same example as documented in document of "JSONAPI-Serializer".
Can anyone tell me the way to deserialize the above data using "JSONAPI-Serilizer" ?
You're missing your deserialization code. Here is mine that works.
The issue what missing "attributes" option for serializer.
var data = [{ id: 1},{ id: 2 }];
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
var JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;
var UserSerializer = new JSONAPISerializer('id', {attributes: ['id']});
var users = UserSerializer.serialize(data);
console.log(users)
var UserDeserialize = new JSONAPIDeserializer();
UserDeserialize.deserialize(users)
.then(a => console.log(a))
I'm working on an app for internal company use and I'm publishing a list of users that qualify as "supervisor" (using alanning:roles.)
I'm also using useraccounts:bootstrap to collect additional information of each user during registration like who their supervisor is.
I have a function that returns the information I need but it only works when I run it in the browser console after the site has loaded.
If I build the array manually and return it, everything works as expected. The point, of course, is that this should be dynamic and grow as the userbase grows.
About all I know is that the code is not running in the context/order I think it is. I've tried various different things just to see what would happen like moving routes.js into /lib (from /client), moving the function definition into a different file, and more!
How can I correct this? I'm fairly new to Meteor so it's completely possible I'm making some other huge mistake and this difficulty I'm having is just a symptom of that. If so, please let me know!
/server/publications.js
Meteor.publish('supervisor-list', function() {
var criteria = {
roles: {$in: ['supervisor']}
};
var options = {
fields: {
'profile.firstName': 1
, 'profile.lastName': 1
}
};
return Meteor.users.find(criteria, options);
});
/client/routes.js
Router.configure({
layoutTemplate: 'layout'
, loadingTemplate: 'loading'
, notFoundTemplate: '404'
, waitOn: function () {
return [
Meteor.subscribe('transactions')
, Meteor.subscribe('supervisor-list')
];
}
, yieldTemplates: {
nav: {to: 'nav'}
, footer: {to: 'footer'}
}
});
/lib/1functions.js
getSupervisors = function () {
var output = [];
var supervisors = Meteor.users.find().fetch();
for (var i = 0; i < supervisors.length; i++) {
output.push({
text: supervisors[i].profile.firstName + ' ' + supervisors[i].profile.lastName
, value: supervisors[i]._id
});
}
//output = [
// {text: 'Person One', value: 'personone'}
// , {text: 'Person Two', value: 'persontwo'}
// , {text: 'Person Three', value: 'personthree'}
//];
return output;
};
/lib/at_config.js
AccountsTemplates.addField({
_id: 'supervisorEmail'
, type: 'select'
, select: getSupervisors()
, required: true
});
Have a look at the Meteor docs (scroll down a bit to "File load order"). /lib/at_config.js is loaded before /lib/functions.js, so getSupervisors is not defined at that point yet.
Not sure how your code is structured in general, so I can not give any pointers as to how I would do this. The documentation is your friend here.
I'm trying to put together an application which uses YUI's DataTable component but I get the "Data error" message. The datasource is configured to get the records from an ASP.NET web method. The records are returned to the client side successfully (I checked it with IE's debugger). My code looks like the following:
YAHOO.example.Basic = function() {
var dsWS_Restaurants = new YAHOO.util.DataSource("/DemoWebSite/RestaurantsWebService.asmx/GetList", { connMethodPost: true });
dsWS_Restaurants.connMgr = YAHOO.util.Connect;
dsWS_Restaurants.connMgr.initHeader('Content-Type', 'application/json; charset=utf-8', true);
dsWS_Restaurants.responseType = YAHOO.util.DataSource.TYPE_JSON;
dsWS_Restaurants.doBeforeParseData =
function(oRequest, oFullResponse, oCallback) {
// checked here if oFullResponse contains the desired results and it does.
}
dsWS_Restaurants.responseSchema =
{
resultsList: 'd.records',
fields: ["id", "name"]
};
var dsWS_Restaurants_ColumnDefs = [
{ key: "id", sortable: true, resizeable: true },
{ key: "name", sortable: true, resizeable: true }
];
var dsWS_Restaurants_DataTable =
new YAHOO.widget.DataTable("basic4", dsWS_Restaurants_ColumnDefs, dsWS_Restaurants, { caption: "dsWS_Restaurants" });
return {
oDS: dsWS_Restaurants,
oDT: dsWS_Restaurants_DataTable
};
} ();
...
Web method look like this:
public Object GetList() {
var restaurants =
new []{
new
{
id="1",
name="Popeyes spinach"
},
new
{
id="2",
name="Big pappas cottage"
}
};
return restaurants.Select (x => new { id = x.id, name = x.name });
}
Any help is welcome and appreciated. Thanks in advance.
I believe that the overridable doBeforeParseData method should return the oFullResponse object...
dsWS_Restaurants.doBeforeParseData =
function(oRequest, oFullResponse, oCallback) {
// checked here if oFullResponse contains the desired results and it does.
return oFullResponse;
}
.. but there may be more to it than just that.
I found out what caused the error. In the responseSchema of the datasource the resultList was defined as 'd.records' but I had no "records" field returned by the web method. I replaced 'd.records' with 'd' and the sample worked. My mistake was that I borrowed the code from a sample application from http://mattberseth.com/blog/2008/09/dynamic_data_experimenting_wit.html which used the "records" field.
Happy coding.