在下面的方法中,我正在从Firebase集合中检索一个文档。
我已经设法记录了我需要返回的值,当 getUserByUserId()
被调用,但我需要将它们以 User
对象。
getUserByUserId(userId: string) {
return of(firebase.firestore().collection("users").where("userId", "==", userId)
.get().then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log("User ID", "=>", doc.data().userId);
console.log("Username", "=>", doc.data().userName);
console.log("Mechanic", "=>", doc.data().isMechanic);
console.log("Location", "=>", doc.data().location);
})
}).catch(err => {
console.log(err);
}));
}
这里是... User
数据需要遵循的结构。
import { PlaceLocation } from './location.model';
export class User {
constructor(
public id: string,
public name: string,
public isMechanic: boolean,
public email: string,
public location: PlaceLocation
) { }
}
谁能告诉我,我怎样才能创建一个... User
对象,并将此数据& 将其返回为 getUserByUserId()
?
用"=",...返回 @angularfire 您可以这样做
constructor(private firestore: AngularFirestore) {
}
getUserByUserId(userId: string) {
return this.firestore
.collection("users", ref => ref.where("userId", "==", userId))
.get()
.pipe(
filter(ref => !ref.empty),
map(ref => ref.docs[0].data() as User),
map(data => new User(data, data.location))
)
}
更新的
如果你需要对象实例,你应该有额外的构造函数,像这样关于对象分配
export class User {
constructor(
public id: string,
public name: string,
public contactNumber: number,
public isMechanic: boolean,
public email: string,
public password: string,
public address: string,
public imageUrl: string,
public location: PlaceLocation
) { }
public constructor(
init?: Partial<User>,
initLocation?: Partial<PlaceLocation>) {
Object.assign(this, init);
if(initLocation) {
this.location = new PlaceLocation(initLocation);
}
}
}
export class PlaceLocation {
constructor() { }
public constructor(init?: Partial<PlaceLocation>) {
Object.assign(this, init);
}
}
因为你读取的数据是没有类型的对象,你只能显式地创建一个新的用户对象,并使用对象中的数据给它分配属性。
getUserByUserId(userId: string) {
return this.firestore
.collection("users", ref => ref.where("userId", "==", userId))
.get()
.pipe(
filter(ref => !ref.empty),
map(ref => ref.docs[0].data() as User),
map(data => new User(data, data.location))
)
}