I have looked for answers to this problem but I can not implement them correctly. Maybe you can tell me the right way.
I'll explain: I want to use typescript generics not to use any more 'Any' in my methods.
I am writing the code and what I would like to do.
IN THE COMPONENT:
this.DatabaseService.getCollection <IUser> ('users', 'lastname'). subscribe (loadData =>
{
this.listUser = loadData;
});
when I call getCollection () I will call the following nested methods:
I want the type (IUser) passed to getCollection () to be forwarded to the nitidicated methods until you reach getCollectionRef () obtaining a return collection of this type: collection
FILE SERVICE: database.service.ts
getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{
// >>>how do I pass the type (T) to getCollectionSnapshot() ?
return this.getCollectionSnapshot (path, sortBy) .pipe (
map (changes =>
{
return changes.map (change =>
{
const data = change.payload.doc.data ();
const id = change.payload.doc.id;
return {id, ... data};
});
}
));
}
getCollectionSnapshot (path: string, sortBy ?: string): Observable <any []>
{
return this.getCollectionRef (path, sortBy) .snapshotChanges ();
}
getCollectionRef (path: string, sortBy ?: string): AngularFirestoreCollection
{
if (sortBy === undefined)
{
return this.afs.collection (path);
}
else
{
return this.afs.collection (path, ref => ref.orderBy (sortBy));
}
}
Thank you ! I hope to fill my gap in generics
I am not sure if i understand your problem. You want to pass the type parameter given for the method getCollection to the methods called within getCollection . If that's the case would this fit for you:
getCollection <T> (path: string, sortBy ?: string): Observable <T []>
{
return this.getCollectionSnapshot<T> (path, sortBy) .pipe (
map (changes =>
{
return changes.map (change =>
{
const data = change.payload.doc.data ();
const id = change.payload.doc.id;
return {id, ... data};
});
}
));
}
getCollectionSnapshot<T> (path: string, sortBy ?: string): Observable <any []>
{
return this.getCollectionRef<T> (path, sortBy) .snapshotChanges ();
}
getCollectionRef<T> (path: string, sortBy ?: string): AngularFirestoreCollection
{
if (sortBy === undefined)
{
return this.afs.collection (path);
}
else
{
return this.afs.collection (path, ref => ref.orderBy (sortBy));
}
}
notice the changes:
getCollectionSnapshot <T> (...
getCollectionRef <T> (...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.