I'm trying to retrieve the data sent from my android app that is formed like this.
I'm trying to do it on JavaScript. I originally did this on Java and it was something like this
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Chat chat = postSnapshot.getValue(Chat.class);
I want to do the same thing on JavaScript but failed when I'm trying to. What I have now is this
class Chat{
constructor(detail,file_name,is_phone,type,user_id){
this.detail = detail;
this.file_name = file_name;
this.is_phone = is_phone;
this.type = type;
this.user_id = user_id;
}
detail(){ return this.detail;}
file_name(){ return this.file_name;}
is_phone(){ return this.is_phone;}
type(){ return this.type;}
user_id(){ return this.user_id;}
}
//Sync obj changes
dbRefObj.on('child_added',snap => {
myChat = new Chat (snap.val());
console.log(myChat);
});
But what I got is everything being set to detail...
The issue here seems to be that you want to spread the values, instead you're just assigning to the first parameter:
In the current implementation snap.val() is assigned to the detail param
class Chat{
constructor(detail, file_name, is_phone, type, user_id){
// ...
}
}
The following implementation will take the corresponding values from inside the snap.val()
class Chat{
constructor({ detail, file_name, is_phone, type, user_id}) {
// The difference is the use of the deconstructive syntax
}
}
Related
I am trying to take benefits of model instance methods, as stated in the doc. So I defined User class as following:
class User extends Model {
addRole(role){
let roles = this. roles;
roles[role] = true;
this.roles = roles;
this.save();
}
removeRole (role) {
let roles = this.roles;
delete roles[role];
this.save();
}
hasRole (role){
return this.roles[role] != null;
}
}
User.init({
// some attributes
,
roles:{
type: DataTypes.JSON,
allowNull: false,
}
}, { sequelize});
I expected to use methods addRole(), removeRole() and hasRole() in any User instance.
The problem that all the methods can't save their changes to database. (Can read only!)
// example
let user = null;
// get the first user to test.
User.findAll()
.then(users =>{
user = users[0];
user.addRole("admin");
console.log(user.roles); // {admin: true}
user.save();
// However the changes don't appear in the database.
});
I had found the answer.
For some reasons, sequelise can't detect the changes of the json object properly. As sequelise is optimised internally to ignore call to model.save() if there is no changes of the model. So, sequelize randomly ignore the save method.
This behavior had no relation with instance method as I believed when I face this problem first time.
To get out of this problem, I had to use :
user.addRole("admin");
user.changed("roles", true); // <<<< look at this;
console.log(user.roles); // {admin: true}
user.save();
Please note that this function will return false when a property from a nested (for example JSON) property was edited manually, you must call changed('key', true) manually in these cases. Writing an entirely new object (eg. deep cloned) will be detected.
Example:
const mdl = await MyModel.findOne();
mdl.myJsonField.a = 1;
console.log(mdl.changed()) => false
mdl.save(); // this will not save anything
mdl.changed('myJsonField', true);
console.log(mdl.changed()) => ['myJsonField']
mdl.save(); // will save
changed method usage
I'm trying to create a blueprint query for a sailsjs v1 model.
The model is a BlogPost which has 2 "options". One is the target and the other one is Status.
If the target is Site and the status is Published, the query should return, otherwise nope. I'm using the default REST routes provided by Sails (blueprints) and everything works fine if I try to find all of them. However, if I try to find one by ID...I can't even get back those that have a status of 'Unpublished'.
This is my code in blueprint.js parseBlueprintOptions ->
parseBlueprintOptions: function (req) {
var queryOptions = req._sails.hooks.blueprints.parseBlueprintOptions(req);
if (queryOptions.using === 'blogpost') {
if (req.options.blueprintAction === 'create') {
queryOptions.newRecord.user_id = req.session.user.id;
return queryOptions;
} else if (req.options.blueprintAction === 'update') {
queryOptions.criteria.where.user_id = req.session.user.id;
queryOptions.valuesToSet.user_id = req.session.user.id;
return queryOptions;
} else {
if (req.session.administrator) {
return queryOptions;
} else {
queryOptions.criteria.where.blogpost_target = 'Site';
queryOptions.criteria.where.blogpost_status = 'Published';
console.log(queryOptions);
return queryOptions;
}
}
}
}
};
Any tips on why the query does not get triggered for findOne? As i said, it returns regardless of the status/target.
Hey 'find' returns object array and 'findone' returns only an object. I guess therefor it won't work!
Every time I load the webpage, I'd have to click the logo in-order my data to fully populate the local array in my component. The data fetched is located in a local JSON file. Having to refresh the page every-single-time is fairly unprofessional/annoying.
Using Angular CLI 1.3.2
Here's where my problem lies:
#Injectable()
export class LinksService implements OnInit{
siteFile : IFile[];
constructor(private http: Http) {
this.getJSON().subscribe(data => this.siteFile = data, error =>
console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get('./assets/docs/links.json')
.map((res:any) => res.json());
}
getAllIpageLinks() : IPageLink[]{
var selectedIPageLinks: IPageLink[] = new Array();
var selectedFileLinks : IFile[] = new Array();
selectedFileLinks = this.siteFile;
for (var i=0; i<selectedFileLinks.length; i++)
{
selectedIPageLinks =
selectedIPageLinks.concat(selectedFileLinks[i].files);
}
return selectedIPageLinks.sort(this.sortLinks);
}
Component:
constructor(private elRef: ElementRef, private linksService: LinksService) {
this._file = this.linksService.getAllIpageLinks();
}
Edit
The title has to be clicked in order for array of IFile[] to completely render. I've tried setting IFile to an empty array (IFile[] = []) The error goes away, however, it will render empty data.
The problem seems to be in the For loop, it can't recognize .length.
Problem :
The codes are correct but the approach is wrong. Subscribing to an Observable getJSON() is async task. Before any data is being returned by getJSON(), you already calls getAllIpageLinks() and therefore you get null value on very first run. I believe since you have injected the service as singleton in component, the data gets populated in subsequent call( on refresh by clicking logo).
Solution:
Apply the changes (that you are making in getAllIpageLinks ) by using map operator on observable.
return the instance of that observable in the component.
subscribe to that observable in the component(not in .service)
Welcome to StackOverflow. Please copy paste your codes in the question instead of giving screenshot of it. I would be able than to give you along the exact codes
Reference Codes :
I haven't tested the syntax but should be enough to guide you.
1. Refactor getAllIpageLinks() as below
public getAllIpageLinks(): Observable<any> {
return this.http.get('./assets/docs/links.json')
.map((res:any) => res.json());
.map(res => {
var selectedIPageLinks: IPageLink[] = new Array();
var selectedFileLinks : IFile[] = new Array();
selectedFileLinks = res;
for (var i=0; i<selectedFileLinks.length; i++)
{
selectedIPageLinks =
selectedIPageLinks.concat(selectedFileLinks[i].files);
}
return selectedIPageLinks.sort(this.sortLinks);
});
}
call above getAllIpageLinks() in your component
and subscribe to it there
I have an Alexa skill which requires to programmatically override the values given by the user.
I have tried nullifying the value and later pass it in as the "updated Intent".
this.event.request.intent.userPrompt.value = null;
var updatedIntent = this.event.request.intent;
this.emit(':elicitSlot', 'userPrompt',"Say something","Say something", updatedIntent);
However, the input JSON shows previous value. Is there a solution to this?
there is
delete this.event.request.intent.slots.<slotname>.value;
var updatedIntent = this event.request.intent;
this.emit(':elicitSlot', <slotname>,"Say something","Say something", updatedIntent);
if you have a slot with a custom slot type you also have to
delete this.event.request.intent.slots.<slotname>.resolutions;
For the version V2 you should update the intent in this way (as far as I know)
handlerInput.responseBuilder
.addDelegateDirective(newIntent)
.getResponse();
newIntent should be an object where you can set your new slot values, for example :
const resetIntent = (handlerInput) => {
const intent = {
name : 'myIntentName',
confirmationStatus: 'NONE',
slots : {
slotOne: {
name: 'slotOne',
confirmationStatus: 'NONE'
}
}
}
return handlerInput.responseBuilder
.addDelegateDirective(intent)
.getResponse();
}
At a loss on this one.
I'm using Ember and Ember data. I've got this extra implementation of ic-ajax to make GET, POST and PUT calls. Anyway, i'm trying to make a GET call then turn those results into model instances.
return this.GET('/editor')
.then((data) => {
return data.drafts.map((draftData) => {
let draft = this.store.find('draft',draftData.id);
console.log(draft.get('type'));
return draft;
});
});
My API returns proper data as data.drafts. This map is supposed to return an array of promises that resolve to draft models. It does not. It resolves to a draft model that has id, date, and title. But that's it. I have 25 others attributions.
In another part of the application i'm getting drafts using findAll on the model. And those models look fine. But when I try store.findRecord('draft',id) i get these fake objects.
-- edit
This is what my ReOpenClass method looks like for getting an array of objects from the server and turning them into ember objects
search(critera) {
let query = { search: critera };
let adapter = this.store.adapterFor('application');
let url = adapter.buildURL('article','search');
return adapter.ajax(url,'GET', { data: query }).then(response => {
let articleRecords = response.articles.map((article) => {
let record;
try {
record = this.store.createRecord('article', article);
} catch(e) {
record = this.store.peekRecord('article', article.id);
}
return record;
});
return articleRecords;
});
},
So far I can't find a better way to pull this off.