返回与用户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>
...

有人能帮我吗

这是因为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 };
}
});
})
);
}

最新更新