Reputation: 3
I am trying to over come this problem and I am can't=> My Console Error as Following:
core.js:6456 ERROR TypeError: Cannot read property 'doc' of undefined at
home.component.ts:22 at Array.map (<anonymous>) at
SafeSubscriber._next (home.component.ts:18) at
SafeSubscriber.__tryOrUnsub (Subscriber.js:183) at
SafeSubscriber.next (Subscriber.js:122) at Subscriber._next (Subscriber.js:72) at
Subscriber.next (Subscriber.js:49) at Notification.observe (Notification.js:20) at
AsyncAction.dispatch (observeOn.js:25) at
angular-fire.js:27
.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Good } from 'src/app/interfaces/good.interface';
import { GoodsService } from 'src/app/services/goods.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
goods :Array<Good> =[];
goodsObservable!: Subscription;
constructor(private gs : GoodsService) { }
ngOnInit (): void {
this.goodsObservable = this.gs.getAllGoods().subscribe(data => {
this.goods = data.map((element:any)=>{
console.log(data);
return {
**id: element.payload.doc.id,
...element.payload.doc.data()**
}
})
})
}
ngOnDestroy (){
this.goodsObservable.unsubscribe();
}
addToCart(id: any) {
console.log("added", id)
}
}
Upvotes: 0
Views: 954
Reputation: 8184
You should verify if data
is an array and that all elements inside data have payload
property. Otherwise, you can use conditional properties like this
return {
**id: element?.payload?.doc?.id,
...element?.payload?.doc?.data()**
}
It avoids to get the error in the console, but still id
will remain null
or undefined
Upvotes: 1