listItemAds() {
this.itemList = this.afs.collection<Class>('Collection');
this.itemList.snapshotChanges().subscribe(list => {
this.itemArray = [];
list.forEach(action => {
const data = action.payload.doc.data() as Class;
this.itemArray.push(data);
--> this.itemArray.reverse(); // I try use this.itemArray.reverse(data.idNumber) ==> error
});
});
console.log(this.itemArray);
}
I wanna reverse data from New data to Old data , I set idNumber in object ex:[1,2,3,4,5].
Note
You can use the orderBy query option in your collection call.
The Firebase documentation on ordering & limiting shows you how to use orderBy specifically.
Using the server to sort data results in better client performance.
this.itemList = this.afs.collection<Class>(
'Collection',
ref => ref.orderBy('idNumber', 'desc')
);
this.itemList.subscribe(list => {
console.log(list);
});
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.
I want to add some data on the bookChapters object, like a random id and inside of it the name of the chapters, I tried this but it doesn't work, after I add the previous data I also want to add a new object "takeAways", like the previous one, inside the random id object.
export const createNewChapter = (bookId, inputText) => {
return async dispatch => {
dispatch(createNewChapterStart());
try {
firebase
.firestore()
.doc(`Users/${bookId}/bookChapters/${inputText}`)
.onSnapshot(querySnapshot => {
//There I want to add the chapters to the firestore database
});
dispatch(createNewChapterSuccess(inputText));
} catch (error) {
dispatch(createNewChapterFail(error));
console.log(error);
}
};
};
I wanna know how to do add from scratch the bookChapters object
The database screenshot shows that the bookChapters object is a map. So to add (populate) this object you need to generate a simple JavaScript object with some properties as “key: value” pairs.
Something along these lines, making the assumption the chapter titles are in an Array:
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i) {
obj[i] = arr[i];
}
return obj;
}
const chapterList = ['Intro', 'Chapter 1', 'Chapter2', 'Conclusion'];
const bookChaptersObj = arrayToObject(chapterList);
firebase.firestore().doc(`Users/${bookId}`).update(bookChaptersObj);
Or, if the document does not already exist:
firebase.firestore().doc(`Users/${bookId}`).set(bookChaptersObj, {merge: true});
I'm struggling to overcome problems that I have on nested onSnapshot, so, in short, I have 3 nested onSnapshot and when parent/root onSnapshot updates it also creates new onSnapshot listeners and leaves old ones too, so old and new ones are listening to the changes. I know that I should unsubscribe it but I can't, I'm losing track of which listeners are added or already exist.
One solution is to create array of unsubscribing functions in parent onSnapshot, but there another problem comes, I'm using docChanges with forEach and it is hard to manage which would I unsubscribe from array.
I saw this on Stackoverflow but it doesn't fit mine or even doesn't explain correctly exactly this case: nested listeners
What can you suggest to me? I don't know what else should I do.
Thanks in advance.
here is an example of my code that I'm trying to implement unsubscribe stuff( I use Mobx):
// TODO: optimise this query
const id = auth().currentUser?.uid;
// get all channelId-s that user has
channelParticipantsRef
.where('user.id', '==', id)
.onSnapshot((userChannels) => {
userChannels?.docChanges().forEach(function (channelParticipant) {
const channelParticipantData = channelParticipant;
if (!channelParticipantData.doc.exists) return;
// get all channels data that user has
channelsRef
.where(
'channelId',
'==',
channelParticipantData.doc.data().channelId,
)
.onSnapshot((channels) => {
if (!channels || channels.empty) return;
channels.docChanges().forEach(function (channel) {
const channelDataObject = channel.doc.data();
console.logBeauty(channel.type, 'channelDataObject ');
if (channel.type === 'added' || channel.type === 'modified') {
const channelData: ChannelTransformedDataType = {
...channelDataObject,
language: channelParticipantData.doc.data().language,
channelParticipantId: channelParticipantData.doc.id,
lastMessageDate: {
...channelDataObject.lastMessageDate,
},
otherUsers: [],
};
// get all channels users
channelParticipantsRef
.where('user.id', '!=', id)
.where('channelId', '==', channelDataObject.channelId)
.onSnapshot((channelParticipants) => {
const participants: UserModelType[] = [];
if (channelParticipants.empty)
return self.removeChannel(
channelDataObject.channelId,
);
channelParticipants.docs.forEach(
(channelParticipant) => {
participants.push(channelParticipant.data().user);
},
);
channelData.otherUsers = participants;
console.log(channelData, 'channelDatachannelData');
if (channel.type === 'added')
self.pushChannel(channelData);
else self.editChannel(channelData);
});
} else if (channel.type === 'removed') {
self.removeChannel(channelDataObject.channelId);
}
});
});
});
});
I'm making a web app to help people create graphs. When a user creates two graphs and deletes the first one, the index in the array changes to 0 and so the second graph (graph1) doesn't get deleted from Firestore. Any ideas on how to approach this? Thanks
Adds Graph
onClick={ () => {
const clientDb = firebaseClient.firestore();
// Adding Graph Options NOTICE HERE SITTING DOCUMENT NAME TO graph${i}
for(var i = 0 ; i < numberofGraphs.length ; i++ ){
clientDb.collection("Users").doc(props.uid).collection("Dashboard").doc(`graph${i}`).set({
type:numberofGraphs[i].type,
title:numberofGraphs[i].type,
seriestitle:numberofGraphs[i].seriestitle,
legend:numberofGraphs[i].legend,
xAxis:numberofGraphs[i].xAxis,
yAxis:numberofGraphs[i].yAxis,
color:numberofGraphs[i].color,
tooltipcolor:numberofGraphs[i].tooltipcolor,
tooltiptextcolor:numberofGraphs[i].tooltiptextcolor,
axisColor:numberofGraphs[i].axisColor,
})
}
}}
Deletes Graph
numberofGraphs.map( (si, k) => (
<>
<CloseIcon
onClick={ () => {
if(window !== "undefined") {
console.log("lets see it")
const clientDb = firebaseClient.firestore();
//NOTICE HERE DELETING Graph with index from map
clientDb.collection("Users").doc(props.uid).collection("Dashboard").doc(`graph${k}`).delete();
}
const newgraphs = numberofGraphs.filter( (object, kk) => k!== kk )
setnumberofGraphs(newgraphs);
}}
/>
<CreateGraph2 type={si.type} title={si.title} seriestitle={si.seriestitle}/>
</>
))
If you absolutely have to do it this way you could "mark doc as deleted" by doing collection('Dashboard').doc('<doc-to-delete>').set({ deleted: true }) and then just filter it out in the client by this property and don't display it.
More generally - use collection().add() to create new documents and let firestore auto-generate IDs for you. Then access your documents by ID, instead of trying to keep track of indices on the front end.
I solved my issue doing the following:
Adds Graph
// Took #samthecodingman's advice by moving all graphs to their own /Graphs collection.
// Which also resonated with #Brian's answer to use
// collection().add() to add documents with Auto-generated ID's instead of adding graphs based
// on index no. of array.
onClick={ () => {
if(window !== "undefined") {
const clientDb = firebaseClient.firestore();
clientDb.collection("Users").doc(props.uid)
.collection("Dashboard")
.doc("First").collection("Graphs").add({
type:type, title:title, seriestitle:seriestitle,
legend:legend,
xAxis:xAxis,
yAxis:yAxis,
color:color,
tooltipcolor:tooltipcolor,
tooltiptextcolor:tooltiptextcolor,
axisColor:axisColor,
//passed an id filed to the object I'm saving
id:type+title
})
}
}}
Deletes Graph
//mapping through an array of objects (si) and then using the get() method with
a query to check for matching ID. Then used the id in the delete method
if(window !== "undefined") {
const clientDb = firebaseClient.firestore();
const docref = clientDb.collection("Users").doc(props.uid)
.collection("Dashboard").doc("First").collection("Graphs");
docref.where("id" , "==", `${si.type}${si.title}`)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
docref.doc(doc.id).delete()
console.log(doc.id, " => ", doc.data() );
});
})
}
i've made an api call to retrieve some data. succesfully.
It;s a sum of total hours of credits..i retrieve
Laravel SQL query:
$result = DB::table('contracts')
->select(DB::raw('SUM(monthly_credits) as Total'))
->get();
return $this->sendResponse($result->toArray(), 'credits retrieved succesfully');
Angular call:
monthlyCredits() {
return new Promise(resolve => {
this.http.get(this.apiUrl+'/api/credits').subscribe(data => {
resolve(data);},
err => {
console.log(err);
});
});
}
home.ts:
monthlyCredits(){
this.restProvider.monthlyCredits()
.then(data => {
this.credits = data['data'];
console.log(this.credits);
});
}
data: [{total: 50.5}]
-> 0: {total: 50.5}
As i display it on the frond-end with {{credits | json }}
it returns
[{"total":50.5}]
Im trying to only display the sum of the total credits, which is 50.5. not the other characters.
Thanks in advance.
You need to access the total property from the credits, change it as follows,
{{credits[0].total}}
You have to set the total to your this.credits or you have to use the fullpath within your html template like {{credits[0].total}}
try following in your home.ts:
monthlyCredits(){
this.restProvider.monthlyCredits()
.then(data => {
this.credits = data['data'][0]['total'];
console.log(this.credits);
});
Make sure you access total only if it is loaded.