简体   繁体   English

类型 void 上不存在 Angular 属性订阅

[英]Angular Property subscribe does not exist on type void

Currently I am getting a firebase document from my component ts file.目前我正在从我的组件 ts 文件中获取一个 firebase 文档。 It is working perfectly.它运行良好。 But when I am trying to move the logic to my service file then trying to subscribe that method from the service in my component getting an error Property subscribe does not exist on type void.但是,当我尝试将逻辑移动到我的服务文件时,然后尝试从我的组件中的服务订阅该方法时出现错误属性订阅不存在于类型 void。 Because I think onAuthStateChanged method returns void.因为我认为 onAuthStateChanged 方法返回无效。 In this case how can i get the currently logged in user uid.在这种情况下,我如何获取当前登录的用户 uid。

Service.ts -服务.ts -

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");
  }
});

Component.ts -组件.ts -

public allPets : any = [];

  constructor(private petservice : PetService) { }

  ngOnInit() {
    this.petservice.getPetsForCurrentUser().subscribe(res => console.log(res));
  }

Inside the component.ts, you can call onAuthStateChanged , inside ngOnInit , do the following:在 component.ts 中,您可以调用onAuthStateChanged ,在ngOnInit ,执行以下操作:

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

Then inisde the service, do the following:然后insde服务,执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM