问题描述
我无法根据用户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 };
}
});
})
);
}