I'm trying to copy the data from firebase to an array using angular 2. But i'm unable to push the data into the array.
Here's the code:
Variables:
uid: string = '';
agencyItems: FirebaseListObservable<any[]>;
trackerItems: FirebaseListObservable<any[]>;
agencyID: any[] = [];
getData()
this.af.auth.subscribe(auth => {
if (auth) {
this.uid = auth.auth.uid;
}
});
this.getAgencyData();
console.log("AgentID: ",this.agencyID);
console.log("Array Length = ",this.agencyID.length); //PROBLEM HERE: Array agencyID is still 0.
this.getTrackerData();
getAgencyData():
console.log("Fetching agency data");
this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
this.agencyItems.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.val()._id);
this.agencyID.push(snapshot.val()._id);
});
});
getTrackerData():
for (let i = 0; i < this.agencyID.length; i++)
{
console.log("Fetching Tracker data");
this.trackerItems = this.af.database.list('/tracker/' + this.agencyID[i]);
this.trackerItems.subscribe(trackerItems => trackerItems.forEach(Titem =>
console.log("Tracker name: " + Titem.name),
));
}
Here is the debug console screenshot:
Since i'm a newbie to web programming some code may seem completely unnecessary.
What am I doing wrong in this code? How can I implement the same.
The problem is the location where, or better WHEN, you are checking the length of the array. You make an asynchronous call when you fetch the data, but you are checking the length of the array before the data has been returned. Therefore the array is still empty.
Try the following in getAgencyData():
console.log("Fetching agency data");
this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
this.agencyItems.subscribe(snapshots => {
snapshots.forEach(snapshot => {
console.log(snapshot.val()._id);
this.agencyID.push(snapshot.val()._id);
console.log("Array Length = ",this.agencyID.length); // See the length of the array growing ;)
});
// EDIT
this.getTrackerData();
});
Related
this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.
The code gets data from indexedDB using this.idb.retrieveData() method inside a service and assigns it to this.offline_texts array, my problem is that I can't iterate through the results, please check the attached image for console.log out put on this.offline_texts array. How can I iterate through this array
this.offline_texts.push(this.idb.retrieveData() || []);
this.offline_texts.forEach((messages) => {
if (messages.status == '0') {
this.messageService.sendMessage(messages)
.subscribe(
data => {
this.messagesAll();
this.status = 'true';
},err =>{
console.log("Error " +err)
});
}
});
console.log(this.offline_texts) outputs the results on the below picture.
Results image
You have an array within an array. And so in your code above messages is also an array, and won't have a status property.
I think the problem is with the first line, where you're pushing into offline_texts, which should probably be:
this.offline_texts = this.idb.retrieveData() || [];
But if you're keeping offline_texts as an array, you need to iterate both:
this.offline_texts.push(this.idb.retrieveData() || []);
// First loop the arrays within offline_text
for (const messages of this.offline_texts) {
// Each item is an array of messages, so we loop once more
for (const message of messages) {
if (message.status == '0') {
this.messageService.sendMessage(message)
.subscribe(data => {
this.messagesAll();
this.status = 'true';
}, err => {
console.log("Error " + err)
});
}
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Simplified:
Use Axios to get data
Place data in an array and end function with return array
The array is passed to function
console log data from the array
why is it returning undefined?
Long Story:
I am re-coding to the Single responsibility principle,
so the function calls and returns weather data,
Later on, create a single function that adds data as elements to the hmtlDom.
I need to be able to select specific variables from the API data,
I'm just learning JSON and I was sure I was doing it wrong, so I simplified the results,
I'm working in Typescript, so it might be a typing issue.
reading through documentation hasn't helped, Last Resort is here.
export function getWeatherData(api : string) {
var weatherData: any = []
axios.get(api)
.then(function (response) {
weatherData.push(response.data.city.name)
})
.catch(function(error){
console.log(error)
})
return weatherData
}
enter image description here console.log(weatherData)
function main() {
var city = getCity()
var api = getApi(city)
let weatherData = getWeatherData(api)
console.log(weatherData)
clearDivs()
addDivs(howManyReadings)
addDataToDivs(weatherData)
}
export function addDataToDivs(weatherData: any) {
// let li = document.getElementsByClassName("weatherInnerContainer")
// let nI = li.length
// for (var i = 0; i < nI; i++) {
console.log(weatherData[0])
// li[i].appendChild(weatherData['city']['name'])
// li[i].appendChild(weatherData['list'][i.toString()]['main']['temp'])
// li[i].appendChild(weatherData['list'][i.toString()]['dt_txt'])
// li[i].appendChild(weatherData['list'][i.toString()]['weather']['0']['description'])
// let nElement = document.createElement('img')
// let iconValue = (weatherData['list'][i.toString()]['weather']['0']['icon']).toString()
// let iconLink = 'https://openweathermap.org/img/wn/' + iconValue + '#2x.png'
// nElement.src = iconLink
// li[i].appendChild(nElement)
// }
}
Console returns: undefined
axios.get is asynchronous function, which happens 'at a some time', while the function you made is synchronous. This means, that execution of getWeatherData() is immediate, and it does not wait for the results of axios.get.
You can solve this by using promises or callbacks, whichever you prefer. Promise based solution would look something like this:
export function getWeatherData(api : string) {
return axios.get(api)
.then(function (response) {
return response.data.city.name
})
.catch(function(error){
console.log(error)
})
}
function main() {
var city = getCity()
var api = getApi(city)
getWeatherData(api).then(weatherData => {
console.log(weatherData)
clearDivs()
addDivs(howManyReadings)
addDataToDivs(weatherData)
}
}
I pretty sure this question was asked many items, however I cannot find an answer to my particular problem, which seems very but I just can't seem to get it working. I have a user model with cart schema array embedded in it. I am trying to add an object to an array and if it exists only update quantity and price, if it is doesn't add to an array. what happens with my code is that it adds a new item when array is empty, it updates the item's quantity and price but it doesn't want to add a new item. I read a bit a bout and as far as I understood I cannot use two different db methods in one request. I would appreciate any help on this, this is the first time I am actually using mongooose.
const CartItem = require('../models/cartModel');
const User = require('../models/userModel');
exports.addToCart = (req, res) => {
const cartItem = new CartItem.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
if (cart.length == 0) {
docs.cart.push(cartItem);
}
let cart = docs.cart;
let isInCart = cart.filter((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (isInCart) {
console.log(cart.length)
} else {
cart.push(cartItem);
console.log(false);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
I actually managed to get it working like this
exports.addToCart = (req, res) => {
const cartItem = new Cart.model(req.body);
const user = new User.model();
User.model
.findById(req.params.id)
.exec((err, docs) => {
if (err) res.sendStatus(404);
let cart = docs.cart;
let isInCart = cart.some((item) => {
console.log(item._id, req.body._id);
if (item._id == req.body._id) {
item.quantity += req.body.quantity;
item.price += req.body.price;
return true;
}
});
if (!isInCart) {
console.log(cart.length)
cart.push(cartItem);
}
if (cart.length == 0) {
cart.push(cartItem);
}
docs.save(function (err, docs) {
if (err) return (err);
res.json(docs);
});
});
};
don't know if this is the right way to do it, but I can both add a new product into my array and update values of existing ones
Maybe your problem hava a simpler solution: check this page at the mongoose documentation: there is a compatibility issue with some versions of mongoDB and mongoose, maybe you need to edit your model code to look like this:
const mongoose = require("mongoose");
const CartSchema = new mongoose.Schema({
//your code here
}, { usePushEach: true });
module.exports = mongoose.model("Cart", CartSchema);
You can find more information here: https://github.com/Automattic/mongoose/issues/5924
Hope it helps.
I have the following method which isn't working correct:
getProducts(): Observable<Product[]> {
let PRODUCTS: Product[];
this.http.get(this.base_url + "api/products")
.subscribe(
(data) => {
for(var i in data) {
PRODUCTS.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
}
},
(error) => {
console.log(error);
});
return of(PRODUCTS);
}
The error I'm getting is this:
TypeError: Cannot read property 'push' of undefined
Now, I know that the PRODUCT array is not accessable from within the subscribe function, but I cannot get the correct solution for it.
Can anyone help me with that. I want to return an Observable<Product[]>.
Thank you in advance!
Edit: Updated to account for the fact that the API seems to return an array-like object rather than a true array.
You want to use map:
getProducts(): Observable<Product[]> {
return this.http.get(this.base_url + "api/products")
.map(data => {
let products = [];
for (let i in data) {
products.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
}
return products;
})
.do(null, console.log);
}
Since #pixelbit's comment keeps getting upvotes despite being wrong, here's an example showing why it is wrong:
// Fakes a HTTP call which takes half a second to return
const api$ = Rx.Observable.of([1, 2, 3]).delay(500);
function getProducts() {
let products = [];
api$.subscribe(data => {
for (let i in data) {
products.push(data[i]);
}
});
return Rx.Observable.of(products);
}
// Logs '[]' instead of '[1, 2, 3]'
getProducts().subscribe(console.log);