繁体   English   中英

我的控制台中的错误=>(core.js:6456 错误类型错误:无法读取未定义的属性'doc')

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

我正在尝试解决这个问题,但我不能=> 我的控制台错误如下:


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

您应该验证data是否是一个数组,并且 data 中的所有元素都具有payload属性。 否则,您可以使用这样的条件属性

   return {
      
      **id: element?.payload?.doc?.id,
      ...element?.payload?.doc?.data()**
    }

它避免在控制台中出现错误,但id仍将保持null或未定义

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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