Calling function in Ionic controller after data loaded - javascript

I am pulling data from firebase and depending on the data, I adjust show a different image. My data is taking time to return and the conditional I wrote doesn't do anything because it runs before the data returns. How do I call the function after my data loads? I tried everything on the ionicView Docs. I also tried window.onload but that doesn't work. Thanks for your help in advance.
var firebaseRef = new Firebase("https://app.firebaseio.com/files/0/" + $stateParams.theId);
firebaseRef.once('value', function(dataSnapshot){
var dumData = dataSnapshot.val().data;
//this is just an integer
if (dumData > 3){
document.getElementById("pic").style.backgroundImage = 'url(img/pic2.png';
}
//Please ignore syntax errors as they do not exist in original code

Your issue is not related with ionic.
once returns a promise. So you should use the success callback to handle your data.
From Firebase once documentation:
// Provide a failureCallback to be notified when this
// callback is revoked due to security violations.
firebaseRef.once('value',
function (dataSnapshot) {
// code to handle new value
}, function (err) {
// code to handle read error
});

Related

Dialogflow: Is this being used in an async call

I'm new to the javascript world and have been tinkering with Actions on Google. I had an action that was previously running but after attempting to simplify my code, I've been running into a new error I cannot seem to figure out. The code is supposed to make a call to a database and return information to the user based on the date they have selected.
Problem:
The code is supposed to make a call to a database and return information to the user based on the date they have selected. The intent seems to break down when I call the URL using axios. When I test my function I receive the following error from the Google Cloud Platform: "Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler?"
app.intent('Moon', (conv, {date}) => {
// Sets date to today if none given
if (!date) {
date = new Date().toISOString();
}
// Slices date string to match date format in database
const dateSlice = date.slice(5, 9);
// Call to row in dabase for the given date
function getData() {
return axios.get(`example.com/search?Date=${dateSlice}`);
}
return getData().then(res => {
res.data.map(con => {
conv.ask(`On X date there will be a ${con.Object1}`);
});
});
});
I don't know much about Promise and await but that seems to be the issue. I'm not sure how I was able to get my code to run before without these objects. I've tried to insert a Promise object before my return but it makes the rest of the function unreachable. I also checked to see if Axios had any updates but it has not, I am on the latest version. Does the error have to do with one of the returns perhaps?
It could be related to Promises, but you seem to be handling them correctly.
The call to axios.get() is returning a Promise...
... which you are returning in getData()...
... which is returned in the 'Moon' Intent handler as part of the getData().then() block.
I suspect more that this is a logic problem. If res.data is an empty array, then there will be no calls to conv.ask(), so you end up not asking anything.
There is also a problem if res.data has more than two items. In this case, you'll generate an error because you've replied with more than two "simple" responses.
Either way - you may wish to log res and/or res.data to make sure you're getting back what you think.

Get an entityName by GUID, despite of what form is loaded at the moment for use in XrmServiceToolkit.Soap.setState()

I'm stuck on the XrmServiceToolkit.Soap.setState() function.
Prerequisites
I'm on studying MS CRM. One of my tasks is to activate and deactivate a record (this time it's a native "contact" record). I've decided to build my solution in a following way (according to other tasks):
On the OnLoad event of my custom entity's form I create a new contact using XrmServiceToolkit (task condition), then update one field in newly created contact. This actually doesn't make sense in production to create something on this event, but nevertheless, is done this way only for my convenience:
function Practice3()
{
let entityToUpdate = CreateRecordWithToolkit("VP_Created by","Xrm Service Toolkit","4F52999B-0E63-EA11-8125-00155D06F203");
alert("Switching to new record!");
Xrm.Utility.openEntityForm("contact", entityToUpdate);
UpdateFieldsWithXrmServiceToolkit(entityToUpdate);
DeactivateAndActivateContact(entityToUpdate);
}
// I don't post the CreateRecordWithToolkit(fname, lname, accountId) and UpdateFieldsWithXrmServiceToolkit(targetEntity) functions 'cos all is Ok there
// and entityToUpdate GUID is passed properly
Between creation and posting updates I send a command to load that newly created form. It does'n activated it at once, but updates are inserted correctly.
Then I pass the same GUID to my next function DeactivateAndActivateContact(targetEntity) and here I stuck.
Question
Can anyone explain or give a hint on how to use the XrmServiceToolkit.Soap.setState() function? I can't get the "entityName" parameter - what is this? How can I get it with having entity's GUID? I was trying to use it like this:
function DeactivateAndActivateContact(targetEntity)
{
let entityName = GetObjectAttribute(targetEntity, "contact", "name");
XrmServiceToolkit.Soap.setState(entityName,targetEntity, "0", "0",false);
Xrm.Page.data.refresh(true).then(null, null);
}
but getting an undefined error.
Is there any way to get an entityName by GUID? 'cos I'm getting the name of current form.
Error is raised when stepping in to this line:
XrmServiceToolkit.Soap.setState(entityName,targetEntity, "0", "0",false);
To Deactivate contact here is below code,
Note Rest API call is Asynchronous and You will have to use execution context and formcontext in Dynamics
Also you could change your other SOAP calls with Rest API. Refer to CRM Rest Builder, it's way easy to build calls with it.
var entity = {};
entity.statuscode = 2;
entity.statecode = 1;
Xrm.WebApi.online.updateRecord("contact", "4A342F12-D248-E211-8669-005056922461", entity).then(
function success(result) {
var updatedEntityId = result.id;
formContext.data.refresh(yes).then(successCallback, errorCallback);
},
function(error) {
Xrm.Utility.alertDialog(error.message);
}
);

How to get the result from firebase first and then redirect to another page?

i have a function in my app to get some data from firebase and after completion of that firebase on function, i need to redirect it to another page.
But in my code when i press the button it will quickly redirect to another bage so the function is not processed. How can i do this?
$('#pg-myb-inde #testBtn').on('click',function(){
myFirebaseRef.orderByChild('emailid').equalTo('mishan#gmail.com').on('value',function(userSnap){
var user=userSnap.val();
// $('#UserPage .person-name').empty();
// $('#UserPage .person-name').append('' +
// '<i class="glyphicon glyphicon-th-list"></i> '+user.fname);
console.log('appended');
console.log(user.fname);
});
location.href = "/another-web-page";
})
Is this what you're looking for?
$('#pg-myb-inde #testBtn').on('click',function(){
var query = myFirebaseRef.orderByChild('emailid').equalTo('mishan#gmail.com');
query.on('value',function(userSnap){
var user=userSnap.val();
location.href = "/another-web-page";
});
})
The only thing I've changed is move the setting of the location into the callback function.
If that is indeed what you're looking for, it may help if you put some logging statements into this code:
$('#pg-myb-inde #testBtn').on('click',function(){
var query = myFirebaseRef.orderByChild('emailid').equalTo('mishan#gmail.com');
console.log('Before Firebase query');
query.on('value',function(userSnap){
console.log('In Firebase callback');
var user=userSnap.val();
location.href = "/another-web-page";
});
console.log('After Firebase query');
})
Now when you run this code, the output is most likely not what you expected:
Before Firebase query
After Firebase query
In Firebase callback
The reason for this is that the data is asynchronously retrieved from Firebase. When you call on() it starts the request to the server. But since it may take a while before the response comes back from the server, your browser doesn't wait for the answer and just continues with the code after the query. When when the data come back from the server, your callback is invoked.

afterSave member Parse Cloud Code not saving

I am attempting to save a username and userId after a user registers into a Runner Class within Parse. For some reason the information is not saving and I am not receiving an error. Can anyone give some advice?
Parse.Cloud.afterSave(Parse.User, function(request){
if(!request.object.existed()){
var RunnerClass = Parse.Object.extend("Runner");
var runner = new RunnerClass();
runner.set("username", request.object.get("username"));
runner.set("userId", request.object.id);
runner.save();
}
});
Your afterSave is incorrectly defined. There is no response for afterSave. Only on beforeSave.
Parse.Cloud.afterSave(Parse.User, function(request) {
...
}
You have to avoid using request.object.existed() in your afterSave trigger because it currently always returns false. This is unfortunately due to a known bug in Parse Cloud which is yet to be fixed. Instead you have to use the workaround given here in the bug report discussion: https://developers.facebook.com/bugs/1675561372679121/
The workaround is to replace request.object.existed() with the following boolean in your afterSave:
var objectExisted = (request.object.get("createdAt").getTime() != request.object.get("updatedAt").getTime());
Also make sure to use request.user instead of request.object in your code

Saving Breeze entities manually and updating keyMappings

I want to manually save entities in Breeze. We just don't have the option (as much as I try to fight for my opinion) to use the SaveChanges(JObject saveBundle) and need to directly hit a 3rd party Web API with a specific URL for POST/PUT requests.
So I am basically looping through EntityManager.getChanges() and then handling Modified, Added, and Deleted entities.
I can handle the "Modified" without any problems. However, on "Added", I know I need to update keyMappings when I add a new entity after successful save but cannot find any documentation on how to do that manually in JavaScript.
I also wanted to see if there any examples in returning any errors. Basically I want to hook into this call:
$http(params).then(
function (response) { // success
console.log(response);
// update key mappings if its an "Added" somehow
// entityAspect.acceptChanges();
dfd.resolve("something eventually");
},
function () { // error
// added error object here and reject changes on this entity? or just show error message?
dfd.reject("error");
});
return dfd.promise;
In case anyone's wondering, I just check the entityAspect.entityState.isAdded() method. Get the new identity returned from my 3rd party and just update the id accordingly. Our system is a little bit nicer in that we have a set key for all of the entities.
Code wise it looks something like this (dfd is a $q defer):
$http(params).then(function (response) { // success
// on add update the instance id with the new instance id
if (entityState.isAdded()) {
var newId = response.data.changedInstance.newId;
entity.Id = newId ;
}
entityAspect.acceptChanges();
dfd.resolve(response.data);
},
function (response) { // error
dfd.reject(response.data);
});

Categories

Resources