简体   繁体   中英

Error in my Console=> (core.js:6456 ERROR TypeError: Cannot read property 'doc' of undefined)

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)
}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM