Angular JS: value not updated after assignment - javascript

I have a scope that is not updated after assignment inside a factory http call.
var form = {}
var requestForm = {}
requestForm['name'] = $scope.brand.name;
requestForm['country'] = $scope.brand.countryCode;
So I'm setting a $scope.mergeId as my initializer as value 0, then the tableFactory.setMergeRequest will call a http call in the factory file and will return an object, with a boolean and an id #.
$scope.mergeId = 0;
//set merge request/id
tableFactory.setMergeRequest(requestForm).then(function(data){
if(data.mergeRequestStatus){
console.log(data);
$scope.mergeId = data.insertedRequestId; //456
}else{
console.log('no merge id');
}
});
form['mergeId'] = $scope.mergeId;
The boolean will be true, and it should assign the id (456) to the $scope.mergeId. Then that scope will be used to assign the form['mergeId'] variable that will be used in another http call.
When I check the console, the form variable is at zero so it's not updated. I took out the initializer but then it's saying is undefined. The http call is sending back data, it's just the scope is not being updated.
Has anyone gone through this issue before? Should I change the setup for this http call? I tried to this, but it's not setting the right value, it's setting an object.
form['mergeId'] = tableFactory.setMergeRequest(requestForm).then(function(data){
if(data.mergeRequestStatus){
return data.insertedRequestId
}else{
return null
}
});
the response I got from this way, is a d, how do i get the value?
Please help, I've been stuck with this issue for a while. Your help will be appreciated.
ADDITIONAL INFO
This is the http call where tableFactory.setMergeRequest is triggered.
var setMergeRequest = function(object){
var mergeRequestCall = {
method: 'POST',
url: CONFIG.PYTHON_API_END_POINT + '/api/mergerequest',
data: object
}
var d = $q.defer();
$http(mergeRequestCall)
.success(function(response){
d.resolve(response);
}).error(function(response){
d.resolve([]);
});
return d.promise;
}
The response is :
{
"insertedRequestId": 456,
"mergeRequestStatus": true
}

You should set the value where the promise is resolved, not set the value to the function
tableFactory.setMergeRequest(requestForm).then(function(data){
if(data.mergeRequestStatus){
form['mergeId'] = data.insertedRequestId;
}else{
form['mergeId'] = null;
}
});

Related

Parse Javascript API Cloud Code afterSave with access to beforeSave values

I'm using Parse Cloud Code to do before/afterSave processing. I'd check the beforeSave value of an attribute in the afterSave hook - for example, do something when parseObj.get('status') transitions from processing => complete. I can get access to the oldVal/newVal for changed attributes in the beforeSave handler, but I can't find a way to pass the oldVal to the afterSave handler without saving as a DB field.
I tried to pass the values as an attribute to the response and response.object objects, neither makes it through to the afterSave
Parse.Cloud.beforeSave('ParseObj', function(request, response) {
var checkDirty, isDirty, parseObj, prevQ;
// request keys=["object","installationId","user","master"]
if (request.object.isNew()) {
return response.success();
} else {
parseObj = request.object;
checkDirty = ['status']; // array of all attrs to check
isDirty = [];
_.each(checkDirty, function(attr) {
if (parseObj.dirty(attr)) {
isDirty.push(attr);
}
});
console.log("isDirty=" + JSON.stringify(isDirty));
if (isDirty.length) {
prevQ = new Parse.Query('ParseObj');
return prevQ.get(parseObj.id).then(function(prevParseObj) {
var newVal, oldVal;
console.log("prevParseObj, id=" + prevParseObj.id);
oldVal = _.pick(prevParseObj.toJSON(), isDirty);
_beforeSave(parseObj, oldVal); // do something here
request.previousValues = oldVal
request.object.previousValues = oldVal
return response.success();
}, function(err) {
return response.error("parsObj NOT FOUND, parseObj.id=" + parseObj.id);
});
} else {
return response.success();
}
}
});
Parse.Cloud.afterSave('ParseObj', function(request) {
var parseObj;
// request keys=["object","installationId","user","master"],
oldVal = request.previousValues // undefined
oldVal = request.object.previousValues // also, undefined
parseObj = request.object;
_afterSave(parseObj, oldVal) // do something else here
return;
});
Any ideas?
I looked into this some more, and I ended up saving to the Parse object temporarily and removing it like this:
//Add the value you need to the object prior to saving using an "oldValue" key
yourPFObject["oldValue"] = value (this is in your SDK somewhere where the save happens)
//Get that value in afterSave in Cloud Code
var old = object.get("oldValue")
//Do whatever you need to do with "old"...
//Remove the temporary old value so it doesn't stay in the database
object.unset("oldValue")
object.save()
I hope that helps. Good luck!

Can we use variable in request param of get rest call in Angularjs?

I want param`s key as variable whose value get substituted.
Following code depicts my problem.
js code
$scope.firstNameAutoSuggestUrl='getFirstName';
$scope.paramName='fname';
$scope.paramValue='sa';
testParamMethod($scope.firstNameAutoSuggestUrl , $scope.paramName, $scope.paramValue)
function testParamMethod (url ,paramName ,paramValue)
{
$http.get('rest/'+url+'?cd='+ (new Date()).getTime(),{params:{paramName:paramValue} } ).success(function(data)
{ }).error(function(data)
{}
);
}
Actual Request formed
'context root'/rest/getFirstName?cd=1417684294261&paramName=sa
Expected Request
'context root'/rest/getFirstName?cd=1417684294261&fname=sa
Is there any way that paramName get substituted to value which I have set.
try this not sure,
function testParamMethod (url ,paramName ,paramValue)
{
var paramsArr = [];
paramsArr[paramName] = paramValue;
$http.get('rest/'+url+'?cd='+ (new Date()).getTime(),{params:paramsArr}).success(function(data){
}).error(function(data){
});
}

Javascript object locking?

I am running into a strange problem with not being able to update properties on an object that is returned as part of a deferred promise.
// Update or Insert status information into the idr_status table
this.updateStatus = function (idrInspData, statusId, submitting)
{
var def = new $.Deferred();
self.getIdrStatus (idrInspData.idr_date).done (function (idrStatus)
{
//status record exists for the day update record
idrStatus.status_msg_id = statusId;
idrStatus.submitted = submitting ? 1 : 0;
idrStatus.modified = 1;
idrStatus.action_needed = statusId.search('+') != -1 ? true : false;
// update the status
self.db.updateRecord (self.idrStatusTableName, idrStatus).always (
function (updateResult)
{
def.resolve(true);
});
}).fail (function (result)
{
def.reject(result);
});
return (def.promise ());
}
The idrStatus object is returned from a SQLite resultset and then converted to a plain JS object then resolved to the done function above. The object comes in but any attempt to edit the properties are simply ignored and the same object is passed Unchanged to the updateRecord function. I am puzzled? Why would the object be locked?

EmberJS: Creating record which has belongsTo

Let me use Posts and Comments to describe my problem. Inside my post_controller I wish to create a new record for a comment for that current post. What is the ember way to do this?
The relation is set like this:
App.Post = DS.Model.extend({
comments: hasMany('comment'),
});
App.Comment = DS.Model.extend({
post: belongsTo('post')
});
Inside my post_controller I want to create a record. I have this inside an action that is triggered from a template:
App.PostController = Ember.ObjectController.extend({
...
actions: {
createComment: function() {
var post = this.get('model'); // Edit: Forgot that I had this declared outside createRecord
var comment = this.store.createRecord('comment', {
content : "content",
post : post // This is where the problem is
});
}
}
});
However, I get an error saying: Uncaught TypeError: Cannot read property 'post' of undefined
How do I declare this relationship? Thanks.
Edit:
The ember-data error comes from this internal function in ember-data.js:
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'), belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key]; // ERROR OCCURS HERE!
if (isNone(belongsTo)) { return null; }
store.fetchRecord(belongsTo);
return belongsTo;
}).property('data').meta(meta);
};
EDIT: Problem solved!
The problem was that I hade given comment an attribute called data. That attribute was in conflict with internal ember. Removing it made my code above work fine.
If you declare your post outside of the createRecord (ie- above the var comment = line)
var postModel = this.get('model');
You might be having an issue w/ the "this" keyword inside the createRecord scope
Update
also, do you get the same result for this.get('model') and this.get('content') (from outside that scope) ?

jQuery deferred not working for me?

I'm trying to use the jQuery when function, in order to wait until an Ajax request completes before proceeding onwards, but am clearly getting something wrong.
My console output looks like this:
geocodeMaster
geocode Canary Wharf
Object
geocode
Object
address is blank, returning 51.501885 -0.190894
proceeding
Uncaught TypeError: Cannot read property '0' of undefined
Object
Object
The final two Objects are the output from the second call to geocode. Why does the code show proceeding before the output of the second call?
My code looks like this:
function geocode(address, geodata) {
console.log('geocode', address, geodata);
geodata['street'] = address;
if (address=="") {
console.log('address is blank, returning ' + current_latlng[0], current_latlng[1]);
return [current_latlng[0], current_latlng[1]];
}
$.ajax({
url: CS_API + 'geocoder.json',
data: geodata,
dataType: 'jsonp',
jsonpCallback: 'places',
success: function(from_data) {
console.log(from_data);
if (from_data.results.result!=undefined){
var from_result = from_data.results.result;
console.log(from_result)
return [from_result.latitude, from_result.longitude];
} else {
return false;
}
},
error: function(data) {
return false;
}
});
}
function geocodeMaster(place_from,place_to) {
console.log('geocodeMaster');
geodata['key'] = CS_API_KEY;
if (current_latlng!=null) {
geodata['n'] = current_latlng[0] + 0.1;
geodata['e'] = current_latlng[1] + 0.1;
geodata['s'] = current_latlng[0] - 0.1;
geodata['w'] = current_latlng[1] - 0.1;
}
var start_coords,finish_coords;
$.when(start_coords=geocode(place_from,geodata),finish_coords=geocode(place_to,geodata)).then(function(){
console.log('proceeding');
console.log(start_coords[0],start_coords[1],finish_coords[0],finish_coords[1]);
});
}
Is the problem that the objects supplied to when() are not Deferred objects? If so, how can I make them into Deferred objects, while keeping the information that I need to collect - start_lat, etc?
You must return a deferred object from the geocode function. Try :
return $.ajax(..
You cannot store the return value directly into values (it does not work the way it's written now). You have to store them somewhere else, so that the line that calls the when simply reads :
$.when(geocode(place_from,geodata),geocode(....
To solve this, you could pass to geocode an empty object, and have that function save its result in it, for example :
var start_coords = {};
var finish_coords = {};
$.when(geocode(place_from,geodata,start_coords),geocode(place_to,geodata,finish_coords) ...

Categories

Resources