Vue Old Array Mirroring New Array - arrays

I have two arrays declared in my data
data() {
return {
infeed_data:[],
infeed_model:[],
}
},
Once the page is mounted, the following method is kicked off
mounted() {
this.get_rolls_infeed()
},
This method makes a call to my api, then assigns the response to both infeed_data and infeed_model. I then do a for loop and create new key/values on the infeed_model, however the new key/values show up in the infeed_data.
get_rolls_infeed(){
var vthis = this;
axios.post(myapiurl)
.then(function(response){
vthis.infeed_data = response.data[0]
vthis.infeed_model = response.data[0]
vthis.infeed_model.forEach(function(record, index){
vthis.infeed_model[index].usage_type = 0
})
})
},
My Vue html
<b>Infeed Data</b>
<p>{{infeed_data}}</p>
<br />
<b>Infeed Model</p>
<p>{{infeed_model}}</p>
Rendered html to show how _data is mirroring _model

Can you try to do this instead of your code?
vthis.infeed_data = response.data[0];
vthis.infeed_model = response.data[0].slice();

Related

Extending $firebaseArray with an extended $firebaseObject

Trying to cut down code repetition, I've set up a $firebaseArray extension as follows:
var listUsersFactory = $firebaseArray.$extend({
$$added: function (snap) {
return new Customer(snap);
},
$$updated: function (snap) {
var c = this.$getRecord(snap.key);
var updated = c.updated(snap);
return updated;
},
});
and the Customer code:
function Customer(snap) {
this.$id = snap.key;
this.updated(snap);
}
Customer.prototype = {
updated: function(snap) {
var oldData = angular.extend({}, this.data);
this.data = snap.val();
// checks and such
}
}
This works wonders when loading, showing and saving a list of customers, and I'm satisfied with it.
Now, the problem lies in retrieving a single customer and its detail page, because the Customer object isn't an extension of $fireObject and is therefore lacking a $save method
Single customer loading:
customersRef.once("value", function(snapshot) {
if(snapshot.child(uuid).exists())
{
customersFactory.customerDetails = new Customer(snapshot.child(uuid));
return deferred.resolve();
}
}
but when I call customersFactory.customerDetails.$save() I get an error
How can I extend my class so that it works for both array and single object uses?
I couldn't find a way to do this, so I ended up using the $firebaseArray and getting single records off that to pass as details, in case anyone's wondering

pushing a nested array into a nested array angularjs

I have a controller that creates a new allegation for a complaint. I can push into the nested (Child table T2), but am not sure why I can't push into a Child table of the child table (T3).
The model in Json look like this:
{
"c_ID": 1,
"received_DT": "2018-01-22T00:00:00",
"aIO": [{
"a_ID": 1,
"c_ID": 9,
"allegs": [{
"alleG_ID": 33,
"Allegation": "Failure..*",
"disc": []
}]
}]
}
My add angular scope looks as below but I am unsure how I am supposed to push the results.
$scope.addAlleg = function () {
var AIOID = this.a.aiO_ID
$scope.errorMessage = "";
var baseURL = "http://localhost:8000/";
$http.post(baseURL + "api/aio/" + AIOID + "/allegs", $scope.newAlleg)
.then(function (alleg) {
$scope.c.aIO[0].allegs.push(alleg);
$scope.newAlleg = {};
}, function (error) {
$scope.errorMessage = "Failed to save new trip" + error;
})
.finally(function () {
$scope.isBusy = false;
})
};
When I copy the link into postman it posts and creates an allegation just fine, but I know my success/do something with the result is wrong.
Controller
[HttpPost("aio/{aioid}/allegs")]
public JsonResult Post(int aioid, [FromBody]AllegationsViewModel vm)
{
try
{
if (ModelState.IsValid)
{
//Map to entity
var newAllegations = Mapper.Map<ALLEGATIONS>(vm);
//Save to Database
_repository.AddAllegations(aioid, newAllegations);
if (_repository.SaveAll())
{
Response.StatusCode = (int)HttpStatusCode.Created;
return Json(Mapper.Map<AllegationsViewModel>(newAllegations));
}
}
}
catch (Exception ex)
{
_logger.LogError("Failed to save new allegation", ex);
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json("Failed to save new allegation");
}
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(" Validation Failed on new checklist");
}
I have tried
$scope.c.aIO[0].allegs.push(alleg);
$scope.c.aIO[0].allegs[0].push(alleg);
$scope.c.aIO.allegs.push(alleg);
but keep getting bad request. My add scope to the T2 (1st Child table) works just fine as I have
$scope.c.aIO.push(response.data);
Also, my html markup looks like this:
<input type="text" ng-model="newAlleg.Allegation"/>
Have you tried $scope.complaints.aIO[0].allegs.push(alleg.data) ?
I am assuming $scope.c is $scope.complaints

Find the identifier of a certain data set in firebase

I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
... : {
invoices: {
},
},
}
I'm doing this by this:
var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
ref.on("value", function(snapshot) {
var list = snapshot.val();
angular.forEach(list, function(item) {
if(item.settings.number == id)
{
console.log(item.id());
invoice.details = item;
}
})
});
Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.
Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
...
});

Add variable to an existing json object

request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
var time = Math.floor((Date.now() - Date.parse($scope.cases[i].date_case_modified))/(60000*60*24));
$scope.cases.duration.push(time);
}
});
Inside the controller I am trying to tack on the cases.duration onto the cases object but it wont add it onto the object that is returned. Any ideas?
I think you just need to introduce a forEach as shown here:
request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
angular.forEach($scope.cases, function (el) {
var time = Math.floor((Date.now() - Date.parse(el.date_case_modified))/(60000*60*24));
el.duration = time;
});
}
});
Hope this helps

passing data to a collection in backbone

So I am trying storing product types from a json file before trying to add them to a collection but am getting some strange results (as in I dont fully understand)
on my router page i setup a variable for cached products as well as product types
cachedProductTypes: null,
productType : {},
products : {},
getProductTypes:
function(callback)
{
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
var self = this;
$.getJSON('data/product.json',
function(data)
{
self.cachedProductTypes = data;
callback(data);
}
);
},
parseResponse : function(data) {
result = { prodTypes: [], products: [] };
var type;
var types = data.data.productTypeList;
var product;
var i = types.length;
while (type = types[--i]) {
result.prodTypes.push({
id: type.id,
name: type.name,
longName: type.longName
// etc.
});
while (product = type.productList.pop()) {
product.productTypeId = type.id,
result.products.push(product);
}
};
this.productType = result.prodTypes;
console.log( "dan");
this.products = result.products;
},
showProductTypes:function(){
var self = this;
this.getProductTypes(
function(data)
{
self.parseResponse(data);
var productTypesArray = self.productType;
var productList=new ProductsType(productTypesArray);
var productListView=new ProductListView({collection:productList});
productListView.bind('renderCompleted:ProductsType',self.changePage,self);
productListView.update();
}
);
}
when a user goes to the show product types page it runs the showProductsType function
So I am passing the products type array to my collection
on the collection page
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
$.each(this.productTypesArray, function(i,prodType){
tmpItem=new ProductType({id:prodType.id, name:prodType.name, longName:prodType.longName});
console.log(prodType.name);
self.add(tmpItem);
});
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
now this doesnt work as it this.productTypesArray is undefined if i console.log it.
(how am I supposed to get this?)
I would have thought I need to go through and add each new ProductType.
the strange bit - if I just have the code
var ProductsType=Backbone.Collection.extend({
model:ProductType,
fetch:function(){
var self=this;
var tmpItem;
//fetch the data using ajax
self.trigger("fetchCompleted:ProductsType");
}
});
return ProductsType;
it actually adds the products to the collection? I guess this means I can just pass an array to the collection and do not have to add each productType?
I guess this means I can just pass an array to the collection and do not have to add each productType?
Yes, you can pass an array to the collection's constructor, and it will create the models for you.
As far as your caching code, it looks like the problem is here:
if (this.cachedProductTypes !== null) {
return callback(cachedProductTypes);
}
The callback statement's argument is missing this - should be return callback(this.cachedProductTypes).

Resources