简体   繁体   English

角5-可观察到的返回错误无法读取未定义的属性

[英]Angular 5 - Observable return error cannot read property of undefined

I'm starting to implement a simple pagination using Spring Rest and Angular 5 inside my angular service when I call my web service using httpClient a get a correct response with the requested page it's display data on my page correctly but there an error the console web browser that there an error inside my *ngFor loop cannot read property of undefined although that the template display results correctly : 当我使用httpClient调用我的Web服务时,我开始在我的angular服务中使用Spring Rest和Angular 5实现简单的分页,并获得正确的请求页面响应,它可以正确显示页面上的数据,但是控制台Web出现错误浏览器在我的* ngFor循环中存在错误,尽管模板显示正确,但无法读取undefined属性:

The problem is in the Service method : getPageClient() and the *ngFor directive This the log of my error : 问题出在Service方法中:getPageClient()和* ngFor指令这是我的错误日志: 在此处输入图片说明

This my service where I used the observable : 这是我使用可观察的服务:

import { Injectable } from '@angular/core';
import {Client} from '../models/Client'
import {PageClient} from '../models/PageClient'
import { Observable, of } from 'rxjs';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import {catchError,map,tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ClientService {

  private url = 'http://localhost:8099/api/clients';

  private urlPage = 'http://localhost:8099/api/clients/get?page=0&size=3';

  getClient(): Observable<Client[]>{
     return this.http.get<Client[]>(this.url)
      .pipe(
           catchError(this.handleError('getClient', []))
      );
  }

 getPageClient(): Observable<PageClient>{
  return this.http.get<PageClient>(this.urlPage)
  .pipe(
    map(response => {
      const data = response;
      console.log(data.content);
      return data ;
    }));
}
  constructor(private http : HttpClient) { }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}

This my model Class : 这是我的模特课:

import {Client} from '../models/Client' ;  

export class PageClient {
    content : Client[];
    totalPages : number;
    totalElements : number;
    last : boolean;
    size : number ;
    first : boolean ;
    sort : string ;
    numberOfElements : number ;
}

This my Component code : 这是我的组件代码:

import { Component, OnInit } from '@angular/core';
import {Client} from '../models/Client' ;
import {PageClient} from '../models/PageClient'
import {ClientService} from '../services/client.service' ;

@Component({
  selector: 'app-clients',
  templateUrl: './clients.component.html',
  styleUrls: ['./clients.component.css']
})
export class ClientsComponent implements OnInit {

  clients : Client[];
  pageClient : PageClient ;

  getClient(): void {
    this.clientService.getClient()
        .subscribe(clients => this.clients = clients);
  }

  getPageClient(): void {
    this.clientService.getPageClient()
        .subscribe(page => this.pageClient = page);

  }
  constructor(private clientService : ClientService) { }

  ngOnInit() {
     this.getClient();
     this.getPageClient();
  }

}

And this my template part that implement the pagination : 这是我实现分页的模板部分:

<nav aria-label="...">
  <ul class="pagination"  *ngIf="pageClient.content" >
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
    <li *ngFor="let page of pageClient.content ; let i=index " class="page-item"><a class="page-link" href="#">{{i}}</a></li>
   <!-- <li class="page-item active">
      <a class="page-link" href="#">2 <span class="sr-only">(current)</span></a>
    </li>-->
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

Can someone helpe me find the problem with my Observable Thanks in advance 有人可以帮助我提前发现我的“可观察的感谢”吗

Because the getPageClient function is asynchronous, pageClient is undefined when the page first loads. 因为getPageClient功能是异步的, pageClient是当第一次加载页面不确定的。 That means when doing pageClient.content , you will get an error. 这意味着在执行pageClient.content ,您将得到一个错误。

Thankfully, Angular provides a useful bit of syntax you can use in the template to avoid this. 幸运的是,Angular提供了一些有用的语法,您可以在模板中使用以避免这种情况。 You should use *ngIf="pageClient?.content" > instead. 您应该改用*ngIf="pageClient?.content" >

The ? ? tells Angular to only read content if pageClient is not null / undefined. 告诉Angular仅在pageClient不为null / undefined时读取content

More info here 更多信息在这里

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

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