0

我无法根据用户 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>
...

有人能帮助我吗

4

1 回答 1

1

这是因为 AngularFiredata()返回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 };
        }
      });
    })
  );
}
于 2020-08-28T00:46:36.773 回答