返回与用户ID相比的值时出错

问题描述

我无法根据用户ID返回数据。

我的功能在data.service.ts

getData() {
  
  return this.Collection.snapshotChanges().pipe(
    map( actions => {      
      return actions.map(a => { 
         const userId = a.payload.doc.data().userId;
         const data = a.payload.doc.data();        
         const id = a.payload.doc.id;        
         
      if(userId == this.currentUserId){ return { id,userId,...data }; }
      
      });      
    })
  );
}

可以,但是半秒钟后出现以下错误=>

core.js:6228 ERROR TypeError: Cannot read property 'userId' of undefined
    at InicialPage_ion_item_sliding_17_Template (template.html:42)
    at executeTemplate (core.js:12156)
    at refreshView (core.js:11995)
    at refreshEmbeddedViews (core.js:13391)
    at refreshView (core.js:12022)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)
    at refreshView (core.js:12051)
    at refreshEmbeddedViews (core.js:13391)
    at refreshView (core.js:12022)

我的html代码是=>

<ion-list lines="none" class="my-ion-list">
  <ion-item-sliding *ngFor="let item of collection">
    <ion-item >      
      <ion-label>        
        <p>Id do usuario: {{ item.userId }}</p>
        <p>Data: {{ item.dia }}</p>
...

有人可以帮我吗

解决方法

这是因为AngularFire data()返回T | undefined。您必须检查数据是否不是undefined,如下所示:

function getData() {
  return this.Collection.snapshotChanges().pipe(
    map(actions => {
      return actions.map(a => {
        const data = a.payload.doc.data();
        if (data === undefined) {
          throw new Error('User is not found');
        }
        const userId = data.userId;
        const id = a.payload.doc.id;

        if (userId == this.currentUserId) {
          return { id,userId,...data };
        }
      });
    })
  );
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...