Array undefined error for my Angular 2 application - arrays

I am facing the below issue where I am trying to save JSON data coming from my API into an array of my Model object. However, when I console.log the array it prints "undefined". I even tried to print a simple array and it still says "undefined". I am not sure if I am missing anything here. My code is given below. Can some one please help as I am new to Angular 2 and TypeScript.
results : Array<Recipes> = new Array(20);
sample = ['one','two','three'];
getResults(): Observable<Recipes[]>{
return this.http.get('<my API here which works perfectly.>')
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
console.log(this.sample); **---> This prints undefined in console**
console.log(body);
console.log(body.pagination.count);
let total_no_of_results = body.pagination.count;
let no_of_results;
for(no_of_results = 0; no_of_results < total_no_of_results; no_of_results++) {
//this.results[no_of_results] = new Recipes();
this.results[no_of_results] = body.data[no_of_results].embed_url; **---> This gives "Cannot set property '0' of undefined" error and program exits**
//this.results.push(image);
}
console.log(this.results);
return this.results;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}

If you want to use this inside extractData you need
.map(this.extractData.bind(this))
or
.map((data) => this.extractData(data))
otherwise this won't point to the current class' instance.

Related

trying to call api with multiple objects react JS

I'm trying to call a specific object within an api but it returns error
...
calling the first one works but when i call the second objects it returns error
here's the code
Api link : https://opentdb.com/api.php?amount=3&difficulty=easy&type=multiple
const [quiz,setQuiz] = React.useState([""])
React.useEffect(() => {
async function getQuiz() {
const res = await fetch(
"https://opentdb.com/api.php?amount=3&difficulty=easy&type=multiple"
);
const data = await res.json();
setQuiz(data.results);
}
getQuiz();
});
return (
<QuizPage
questionOne={quiz[0].question} //this works //
questionsTwo={quiz[1].question} //this not //
/>
);
I tried to create separate states but it did not work either
i tried to create a seperate state and calling a second object but that didnt work either, i also tried to map over it and still didnt work, i tried many other methods to call api but still no solutions and i get this error in the console ncaught TypeError Cannot read properties of undefined reading 'question, Consider adding an error boundary to your tree to customize error handling behavior, logCapturedError
const [quiz,setQuiz] = React.useState([""])
Your initial sate has only one element, so quiz[1] is undefined, and quiz[1].question will throw an error. You will need to check for the case where you don't have data and either show nothing, or show some loading screen. For example:
const [quiz,setQuiz] = React.useState(null)
// ...
if (!quiz) {
return <div>Loading...</div>
} else {
return (
<QuizPage
questionOne={quiz[0].question}
questionsTwo={quiz[1].question}
/>
);
}

Cannot read property 'data' of undefined discord.js

Making a command to take a random photo of a waifu in this case, and posting it in the channel
Code here:
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
got('https://waifu.pics/api/sfw/waifu').then(response => {
let content = JSON.parse(response.body);
let waifuUrl = content[0].data.children[0].data.url;
let waifuImage = content[0].data.children[0].data.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.user}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
The API should be correct. After a few small changes, I tried console logging the JSON and it did output the correct thing. But when running the code in discord, it outputted a TypeError: Cannot read property 'data' of undefined error. I cannot seem to figure out the problem
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
get('https://waifu.pics/api/sfw/waifu').then(response => {
let content = response.body;
let waifuUrl = content.url;
let waifuImage = content.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.username}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
You thought a little bit complicated ^^ You had something with children and data, although the API just gives an URL. You don't even have to parse it. And you have used the function got(), which you have to replace with get().
I fixed your code just copy it from above.

Cannot read property 'hasOwnProperty' of undefined after updating user

I have came across this bug. When I am updating a user I get following error from the interface:
Cannot read property 'hasOwnProperty' of undefined
The weird thing is, the user updates even when this error message is displayed. Also, there is no error in developer console.
Here is the part of the code in my ODataProvider that should update the user.
case UPDATE:
url = `${apiUrl}/${resource}(${params.id})`;
options.method = 'PUT';
params.data = removeProperties(params.data, ['id', 'odata', 'odata.metadata']);
options.body = JSON.stringify(params.data);
break;
removeProperties constant:
const removeProperties = (data, props) => {
for (let prop of props) {
delete data[prop];
}
return data;
}
Any idea how to solve this?
Thank you in advance.

Troubles with Promises

I'm doing an Ionic project and I'm getting a little bit frustrated whit promises and '.then()' although I've read a lot of documentation everywhere.
The case is that I have one provider with the functions loadClients and getWaybills.
The first one gets all the clients that have waybills and the second one gets all the waybills from one concrete client.
loadClients() {
return new Promise(resolve => {
this.http.get('http://localhost/waybills?fields=descr1_sped&idUser='+ this.id)
.map(res => res)
.subscribe(data => {
this.data = data.json();
resolve(this.data);
});
});
}
// GET WAYBILLS
getWaybills(client) {
return new Promise(resolve => {
this.http.get('http://localhost/waybills/?stato=0&idUser='+ this.id +'&descr1_sped='+ client)
.map(res => res)
.subscribe(data => {
this.data = data.json();
resolve(this.data);
});
});
}
On the other hand, on the component welcome.ts I have a function loadWaybills which is called on the view load and is executing the following code, my idea is to get all the clients and then get the respective waybills of each one. Then I'll take just of the ones that are defined.
The problem is that on the second .then() instead of getting the variable data I'm getting just undefined... I've understood that if you put a synchronous code inside .then() can be properly executed and work with the "data" which is the result of the promise. Why am I getting this undefined?
loadWaybills() {
//We first load the clients
this.waybills.loadClients()
.then(data => {
this.waybill = data;
var preClients = this.waybill;
this.clients = [];
//Here we're deleting duplicated clients and getWaybills of them)
for (let i = 0; i < preClients.length; i++) {
if (this.clients.indexOf(preClients[i].descr1_sped) == -1) {
this.waybills.getWaybills(preClients[i].descr1_sped)
.then(data => {
**//Here we'll check if the clients has waybills or not**
this.clientWaybills[i] = data;
this.clients.push(preClients[i].descr1_sped)
});
}
}
});
}
It is hard to say because we don't know what the API is meant to return. For example, there may be a missing field somewhere from the first GET and now for the second one, it returns as undefined sometimes. If it only returns undefined sometimes, a simple solution to this, would be to check that the value is defined before assigning it to the variable.
If it always returns as undefined and shouldn't, try to debug the code and make sure that the values are present before the second .then.

Updated to angularfire 0.8 resulted in a TypeError

I followed along Thinksters tutorial about firebase and angularjs
It worked great but I wanted to use the new functionality of $asArray() which required an update of angularfire (0.8).
Somehow this results in different TypeError (TypeError: undefined is not a function). For instanc on:
var query = $firebase(ref.startAt(authUser.uid).endAt(authUser.uid));
query.$on('loaded', function () { //ERROR LINE
setCurrentUser(query.$getIndex()[0]);
and
findByUsername: function (username) {
if (username) {
return users.$child(username); //ERROR LINE
}
}
I'm still able to sign in which means that i have connetction with Firebase. Does anybody have an idea of what went wrong or if I have to update anything more to get this working again?
EDIT:
my setCurrentUser-method:
function setCurrentUser (username) {
$rootScope.currentUser = User.findByUsername(username);
}
I've made an attempt to change my findByUsername-method:
findByUsername: function (username) {
if (username) {
return (users.$getRecord(username));
}
}
(relates to)
var ref = new Firebase(FIREBASE_URL + 'users');
var users = $firebase(ref).$asArray();
Still don't know a good way to search through my firebase-array correctly without .$child(username). Do I need a loop?

Resources