Reputation: 2445
Below are a couple of documents I am retrieving from firestore:
Here is the method I'm using:
private _mechanics = new BehaviorSubject<User[]>([]);
fetchMechanics() {
return of(
firebase.firestore().collection("users").where("isMechanic", "==", false)
.get()
.then((docs) => {
const data = []
docs.forEach((doc) => {
data.push(doc);
});
console.log('Service Data:', data);
this._mechanics.next(data)
}).catch((err) => {
console.log(err);
})
);
}
Now I want to convert the data to follow my UserData
interface:
interface UserData {
userId: string,
userName: string,
isMechanic: boolean,
location: PlaceLocation
}
Can someone please tell me what changes I need to make to fetchMechanics()
to do this?
Here's an example of the data in firestore:
Also, I've been trying to copy the below code, but it hasn't worked so far:
private _users = new BehaviorSubject<User[]>([]);
fetchUsers() {
return this.http
.get<{ [key: string]: UserData }>('firebaseUrl/users.json')
.pipe(map(resData => {
const users = [];
for (const key in resData) {
if (resData.hasOwnProperty(key)) {
users.push(
new User(
key,
resData[key].userName,
resData[key].isMechanic,
resData[key].location)
);
}
}
return users;
}),
tap(users => {
this._users.next(users);
})
);
}
Upvotes: 1
Views: 1606
Reputation: 11
this is how I did it
getloc(){
const db = this.fire.firestore;
db.collection("buses").get().then((data)=>{
console.log(data.docs.map(bus=>bus.data()));
});
}
Upvotes: 0
Reputation: 2795
if data in collection have same structure as interface you can just cast object to interface as follow
interface UserData {
userId: string,
userName: string,
isMechanic: boolean,
location: PlaceLocation
}
private _mechanics = new BehaviorSubject<UserData[]>([]);
constructor(private firestore: AngularFirestore) {
}
fetchMechanics() {
return this.firestore
.collection("users")
.ref
.where("isMechanic", "==", false)
.get().then((querySnapshot) => {
const data: UserData[] = [];
querySnapshot.forEach((doc) => {
data.push(doc.data() as UserData);
console.log(doc.id, " => ", doc.data());
});
this._mechanics.next(data)
});
}
Upvotes: 3