簡體   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