角度属性订阅在类型空上不存在



目前我正在从我的组件ts文件中获取Firebase文档。它正在完美地工作。但是当我尝试将逻辑移动到我的服务文件时,尝试从我的组件中的服务订阅该方法,出现错误 属性订阅在类型 void 上不存在。因为我认为 onAuthStateChanged 方法返回 void。在这种情况下,我如何获取当前登录的用户 uid。

服务网 -

getPetsForCurrentUser(){
this.afAuth.auth.onAuthStateChanged((user) =>{
if(user){
// this.afs.collection('pets', ref => ref.where('OwnerID', '==', user.uid)).
this.afs.collection('pets', ref => ref.where('OwnerID', '==', user.uid)).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
}))
).subscribe(docs => {
// loop through each item in the array and log value
docs.forEach(doc => {
return doc;
});
});
}else {
console.log("No user logged in");
}
});

组件.ts -

public allPets : any = [];
constructor(private petservice : PetService) { }
ngOnInit() {
this.petservice.getPetsForCurrentUser().subscribe(res => console.log(res));
}

在 component.ts 中,你可以调用onAuthStateChanged,在ngOnInit中执行以下操作:

ngOnInit() {
this.afAuth.auth.onAuthStateChanged((user) =>{
if(user){
this.petservice.getPetsForCurrentUser(user).subscribe(res => console.log(res));
}
});
}

然后初始化服务,执行以下操作:

getPetsForCurrentUser(user){
return this.afs.collection('pets', ref => ref.where('OwnerID', '==', user.uid)).snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return { id, ...data };
}))
);
});

最新更新