Angularfire2 在没有监听器的情况下获取单个文档
Angularfire2 get single document without listener
我正在使用 angularfire2 v6 和 angular 11。我只是想根据用户的电子邮件从用户集合中获取单个文档。我不想使用 valueChanges()
或 snapshotChanges()
,因为用户对象不会更新,如果是,我不关心获得实时更新。我只想在用户导航到他们的个人资料时获取一次数据。我已经看到您应该可以使用 get()
而不是上述方法,但我无法使任何东西正常工作。
这样做很好:
let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
// subscribe to changes
query.subscribe(queriedItems => {
this.item = queriedItems[0];
this.firstName = this.item.firstname;
this.lastName = this.item.lastname;
this.email = this.item.email;
this.role = this.item.role;
this.lead = !!this.item.lead;
});
但是,再说一遍,valueChanges()
不是天生就一直在听更新吗?我不想那样做。将 .valueChanges()
替换为 .get()
意味着我无法订阅,并且使用 toPromise().then()
似乎只是 return 垃圾而不是实际文档。
完全不知道如何使 get()
工作,但我确实找到了解决方法,将其设置为订阅,然后在获得数据后取消订阅。
this.fireAuth.currentUser.then((res) => {
let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
// subscribe to changes
this.profileSubscription = query.subscribe(queriedItems => {
this.item = queriedItems[0];
this.firstName = this.item.firstname;
this.lastName = this.item.lastname;
this.email = this.item.email;
this.role = this.item.role;
this.lead = !!this.item.lead;
//Unsubscribe here if you don't want an active listener to show changes
this.profileSubscription.unsubscribe();
});
});
我正在使用 angularfire2 v6 和 angular 11。我只是想根据用户的电子邮件从用户集合中获取单个文档。我不想使用 valueChanges()
或 snapshotChanges()
,因为用户对象不会更新,如果是,我不关心获得实时更新。我只想在用户导航到他们的个人资料时获取一次数据。我已经看到您应该可以使用 get()
而不是上述方法,但我无法使任何东西正常工作。
这样做很好:
let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
// subscribe to changes
query.subscribe(queriedItems => {
this.item = queriedItems[0];
this.firstName = this.item.firstname;
this.lastName = this.item.lastname;
this.email = this.item.email;
this.role = this.item.role;
this.lead = !!this.item.lead;
});
但是,再说一遍,valueChanges()
不是天生就一直在听更新吗?我不想那样做。将 .valueChanges()
替换为 .get()
意味着我无法订阅,并且使用 toPromise().then()
似乎只是 return 垃圾而不是实际文档。
完全不知道如何使 get()
工作,但我确实找到了解决方法,将其设置为订阅,然后在获得数据后取消订阅。
this.fireAuth.currentUser.then((res) => {
let query = (this.firestore.collection('users', ref => ref.where('email', '==', res.email)).valueChanges());
// subscribe to changes
this.profileSubscription = query.subscribe(queriedItems => {
this.item = queriedItems[0];
this.firstName = this.item.firstname;
this.lastName = this.item.lastname;
this.email = this.item.email;
this.role = this.item.role;
this.lead = !!this.item.lead;
//Unsubscribe here if you don't want an active listener to show changes
this.profileSubscription.unsubscribe();
});
});