I have this code that gets some data from a MongoDB and saves it in an array in my component.
this.laugService.getAllLaug().subscribe(laug => {
this.laugs = laug; //save posts in array
});
this.laugs.array.forEach(element => {
this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
});
After that i want to save this data to a different array, where i create new instances of my model "Laug". For this i am using a foreach loop, however i am getting an error when running this code:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property
'forEach' of undefined
TypeError: Cannot read property 'forEach' of undefined
I am certain that i receive the data from the DB, however i am unsure why my array is undefined at this point.
Your subscription is asynchronous. The laugs property may not be set when you are trying to iterate. Just put the forEach code inside the subscribe callback:
this.laugService.getAllLaug().subscribe(laug => {
this.laugs = laug; //save posts in array
if (this.laugs && this.laugs.array) {
this.laugs.array.forEach(element => {
this.modelLaugs.push(new Laug(element.navn, element.beskrivelse))
});
}
});
Related
I'm updating the 'backgroundColor' property of the all the objects nested within a sliderSegmentStyleDict state object using the following:
setSliderSegmentStyleDict(prevState => {
let updatedSegmentStyleDict = prevState
for(let segmentIndex in Object.keys(updatedSegmentStyleDict)) {
segmentIndex = Object.keys(updatedSegmentStyleDict)[segmentIndex]
let segmentDict = updatedSegmentStyleDict[segmentIndex]
segmentDict['backgroundColor'] = snappedSegmentIndex > segmentIndex ? '#19486A' : '#d1d5db'
updatedSegmentStyleDict[segmentIndex] = segmentDict
}
return updatedSegmentStyleDict
})
The first time the component renders, it works fine and sets the appropriate colour.
However, when I subsequently invoke this function manually, I get the following error in the console:
Uncaught TypeError: Cannot assign to read only property 'backgroundColor' of object '#<Object>'
Why am I unable to modify the backgroundColor property of segmentDict object?
i have an API whose response is given below in the screenshot. I want to fetch data of my array object and display on the web page. But I got undefined as an output, while i have data in my array object. Please tell me where am doing wrong.
services code:
testfxn(){
return(
this.apiCallService.GET(`${this.myService.myendpoint.xyz}`)
.pipe(
map((testData)=>{
let testresp=testData.response[4];
return testresp;
})
)
);
}
component.ts:
testing(){
this.reportService.testfxn().subscribe((r)=>{
this.resp=r
console.log(this.resp)
})
}
testing(){
this.reportService.testfxn().subscribe((data) => {
this.testingdate=data;
console.log(this.testingdate);
});
}
testfxn() is an asynchronous function. It is possible that your console.log gets executed before the function returns data and is consumed by subscribe()
I'm using JSON.stringify() on array of object before writing to the .json file. I receive an error about circular referencing.
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at TASKS.save (/home/yury.stanev/menlolab/runner/lib/tasks.js:89:27)
at Timeout.setInterval [as _onTimeout] (/home/yury.stanev/menlolab/runner/lib/tasks.js:124:12)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10)
Using unil.inspect I've the found the circular reference line 37 of the following object. I'm trying to use a custom toJSON() method to filter it out. I'm not sure how to actually access the required property to do it. My code is as follows:
toJSON() {
const cleanObj = {};
for (const prop in this) {
if (this.hasOwnProperty(prop) && prop !== '_task' && prop !== '_handle') {
cleanObj[prop] = this[prop];
}
}
return cleanObj;
}
What's the best way to go about solving this issue?
There are two main ways to solve this issue:
One is to use cycle.js which introduces two functions, JSON.decycle() and JSON.retrocycle(), which makes it possible to encode and decode cyclical structures and dags into an extended and retrocompatible JSON format.
Or you can implement your own solution which will require finding and replacing (or removing) the cyclic references by serializable values.
The snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of JSON.stringify():
var circularReference = {otherData: 123};
circularReference.myself = circularReference;
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(circularReference, getCircularReplacer());
Please refer here for more information.
I am trying to display a reference field from my database as a result on my filtered repeater. I am unsure of how to code the page correctly for this to happen.
When testing my code, this is what shows in the developer console:
Loading the code for the SEARCH WITH VIN page. To debug this code, open i5zkm.js in Developer Tools.
Url: https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/19UUA96299A543965/?format=jsonVINModule.jsw
Line 5{...}
SEARCH WITH VIN
Line 14{...}
VINModule.jsw
Line 12
Dataset is now filtered
SEARCH WITH VIN
Line 22
TypeError: Cannot read property 'items' of undefined
import {getVINInfo} from 'backend/VINModule';
import {wixData} from 'wix-data';
$w.onReady(function () {
//TO DO: Write Your Page Related Code Here:
});
export function button1_click(event, $w) {
//Add your code for this event here:
getVINInfo($w("#vininput").value)
.then(VINInfo => {
console.log(VINInfo)
$w("#results").text = VINInfo.Results[8].Value + " " + VINInfo.Results[5].Value + " " + VINInfo.Results[7].Value;
$w("#dataset1").setFilter(wixData.filter()
.eq("year", VINInfo.Results[8].Value)
.eq("make", VINInfo.Results[5].Value)
.eq("year", VINInfo.Results[7].Value))
.then((results) =>{
console.log("Dataset is now filtered");
$w("#repeater1").data = results.items;
let items = "title"
})
.catch((err) => {
console.log(err);
});
$w("#repeater1").expand();
})
}
I expect the repeater to show the title field from my database but nothing happens to the elements in the repeater and I receive the following in my developer console when previewing the page: TypeError: Cannot read property 'items' of undefined.
dataset setFilter() returns a promise with a void value, so you can't just access the dataset items from that returned promise.
If the repeater isn't already bound to the dataset, you should use getItems():
$w("#myDataset").getItems()
.then( (result) => {
$w("#repeater1").data = results.items
})
I've got two types of docs in pouchdb:
todos - list of todos
user - just user number put in pochdb by separate form
When I write todos I also have variable for userNo. This way I know which todos he owns.
I've got two functions in provider to get todos, and user number.
In html list I want to filter todos by user number through pipe:
<ion-item-sliding *ngFor="let todo of todos | filter : 'numer_p' : this.todoService.userNo">
If I enter this number by hand it works great. Todos are filtered by this number.
The problem is that I have two calls in home.ts ionViewLoaded:
//call provider to get all docs to show on the list
this.todoService.getTodos().then((data) => {
this.todos = data;
});
//call provider to get userNo from pouchdb and set variable in the provider
this.todoService.getUser().then((result) => {
console.log("getBadacz result:" + JSON.stringify(result));
this.todoService.userNo = result['name'];
}).then(function(second){;
console.log("second");
});
I need to call getTodos AFTER getUser. So I need to run this functions in sequence using Promises.
Without it this.todoService.userNo in filter is undefined, because it is not set yet. And it will not work.
I tried to do it like this:
this.todoService.getUser().then((result) => {
console.log("getBadacz result:" + JSON.stringify(result));
this.todoService.userNo = result['name'];
}).then(function(second){;
console.log("second");
this.todoService.getTodos().then((data) => {
this.todos = data;
});
});
But there is an error:
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'todoService' of null
I tried to arrange this promises in sequence but without success.
Here is fiddle where you can find implementation of functions in provider:
Filter pouchdb docs by userID saved in another doc
Thank you very much for your help.
In situation like this, I would try to include userId in the todo key, that would increase performance (a todos document may have key like this userId_todoId).
So you will not need two promises at all.