Angular: ERROR TypeError: Невозможно прочитать свойство undefined, вопросительный знак не работает, с данными - PullRequest
0 голосов
/ 13 октября 2019

Как мне исправить ошибку? Ошибка типа: невозможно прочитать свойство 'products' из неопределенного. Я поставил знак вопроса? в представлении HTML в соответствии с ресурсом. Мы получаем данные из API, я вижу правильные данные в данных консоли chrome f12.

Angular 6 - ОШИБКА TypeError: Невозможно прочитать свойство 'value' из неопределенного

**ProductConnectService.ts**

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';

    @Injectable({
      providedIn: 'root'
    })

    export class ProductconnectService {
      private headers: HttpHeaders;
      private accessPointUrl: string = 'http://localhost:40085/Products1';

     constructor(private http: HttpClient) {
        this.headers = new HttpHeaders({'Content-Type': 'application/json; charset=utf-8'});
       }

       public getAll() {
        // Get all product data
        return this.http.get('http://localhost:40085/api/products2')
      }
    }

**Product.component.ts**

    import { Component, OnInit } from '@angular/core';
    import { ProductconnectService } from '../productconnect.service'

    @Component
    ({
      selector: 'app-product',
      templateUrl: './product.component.html',
      styleUrls: ['./product.component.css']
    })

    export class ProductComponent implements OnInit 
    {
       products: any = {};
       constructor(private productconnectService: ProductconnectService) {}


       ngOnInit() 
       { 
         this.productconnectService.getAll().subscribe((data: any)=>{
            console.log(data);
            this.products = data;
        })
      };
    }

**Product.html**

     <ng-container *ngFor="let productsingle of data.products" >
       <div class = "productname" > {{productsingle?.productName}}  </div>
     </ng-container>


**Error:**

>ProductComponent.html:3 ERROR TypeError: Cannot read property 'products' of undefined
    at Object.eval [as updateDirectives] (ProductComponent.html:3)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:20349)
    at checkAndUpdateView (core.js:19745)
    at callViewAction (core.js:19986)
    at execComponentViewsAction (core.js:19928)
    at checkAndUpdateView (core.js:19751)
    at callViewAction (core.js:19986)
    at execComponentViewsAction (core.js:19928)
    at checkAndUpdateView (core.js:19751)
    at callWithDebugContext (core.js:20639)

Выход API:

[{"productId":1,"productName":"Samsung T3 Portable SSD - 500GB","productDescription":"Superfast Read-Write Speeds of up to 450 MB/s; Shock Resistant & Secure Encryption","unitPrice":5.5,"imageLocation":"Product1.jpg","productCategoryId":1,"productCategory":null},{"productId":2,"productName":"Acer R240HY bidx 23.8-Inch IPS HDMI DVI VGA (1920 x 1080) Widescreen Monitor","productDescription":"The Acer R240HY 23.8” IPS display shows every detail clearly and vivid without color difference from any viewing angle. Its zero frame design puts no boundary on your visual enjoyment while the brushed hairline finish stand matches any environment. It also supports VGA, DVI & HDMI inputs so you can easily power and extend the enjoyment from your smartphone or tablet on Full HD display.","unitPrice":4.2,"imageLocation":"Product2.jpg","productCategoryId":null,"productCategory":null},{"productId":3,"productName":"Panasonic On-Ear Stereo Headphones RP-HT21 ","productDescription":"Lightweight, open-air design on-ear headphones weigh just 1.2 oz. (without cable). Connectivity Technology: Wired;30mm large neodymium drivers deliver rich powerful bass and natural treble.","unitPrice":9.8,"imageLocation":"Product3.jpg","productCategoryId":3,"productCategory":null},{"productId":4,"productName":"Canon TS8220 Wireless All in One Photo Printer, Black","productDescription":"Introducing the sleek and streamlined PIXMA TS8220 Wireless Inkjet All-In-One home printer, available in Black, White and Red color options. The PIXMA TS8220 is a high-end Inkjet All-In-One printer designed with fast prints, robust features and lots of connectivity options in mind. ","unitPrice":1.4,"imageLocation":"Product4.jpg","productCategoryId":null,"productCategory":null}]

Ответы [ 2 ]

0 голосов
/ 13 октября 2019

, если объект данных имеет массив product:

products=[];
    ngOnInit() 
           { 
             this.productconnectService.getAll().subscribe((data: any)=>{
                console.log(data);
                this.products = data.products;
            })
          };

и ваш html должен быть

<ng-container *ngFor="let productsingle of products" >
       <div class = "productname" > {{productsingle?.productName}}  </div>
     </ng-container>

и если ваши данные, зарегистрированные в консоли, имеют вид:

 [{"productId":1,"productName":"Samsung T3 Portable SSD - 500GB" , .....

это должно работать:

 products=[];
        ngOnInit() 
               { 
                 this.productconnectService.getAll().subscribe((data: any)=>{
                    console.log(data);
                    this.products = data;
                })
              };
0 голосов
/ 13 октября 2019

Свойство data не определено.

Вы должны изменить data.products на products.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...