【问题标题】:Angular Property subscribe does not exist on type void类型 void 上不存在 Angular 属性订阅
【发布时间】:2020-01-02 18:48:07
【问题描述】:

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

Service.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 -

public allPets : any = [];

  constructor(private petservice : PetService) { }

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

【问题讨论】:

  • 为什么不能在组件内部调用this.afAuth.auth.onAuthStateChanged((user) =>{
  • 那我将如何检查 OwnerID === user.uid?

标签: angular firebase google-cloud-firestore


【解决方案1】:

在component.ts里面,可以调用onAuthStateChanged,在ngOnInit里面,做如下操作:

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

然后 inisde 服务,执行以下操作:

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

【讨论】:

  • 在我订阅它的组件 ngOnInit 中,它说“void”类型上不存在属性“订阅”
  • 在此处添加退货return this.afs.collection('pets', ref => ref.where('OwnerID', '==', user.uid)).snapshotChanges().pipe(
猜你喜欢
  • 1970-01-01
  • 2018-11-30
  • 2019-01-03
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
相关资源
最近更新 更多