gpt4 book ai didi

angular - 如何将 Firebase 中的查询快照转换为不同的对象?

转载 作者:行者123 更新时间:2023-12-05 02:07:35 24 4
gpt4 key购买 nike

在下面的方法中,我从 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() 的响应返回?

最佳答案

@angular/fire你可以这样做

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))
)

}

已更新

如果你需要对象实例,你应该有这样的额外构造函数 about object assign

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))
)

}

关于angular - 如何将 Firebase 中的查询快照转换为不同的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61621991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com