簡體   English   中英

角5-可觀察到的返回錯誤無法讀取未定義的屬性

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

當我使用httpClient調用我的Web服務時,我開始在我的angular服務中使用Spring Rest和Angular 5實現簡單的分頁,並獲得正確的請求頁面響應,它可以正確顯示頁面上的數據,但是控制台Web出現錯誤瀏覽器在我的* ngFor循環中存在錯誤,盡管模板顯示正確,但無法讀取undefined屬性:

問題出在Service方法中:getPageClient()和* ngFor指令這是我的錯誤日志: 在此處輸入圖片說明

這是我使用可觀察的服務:

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

這是我的模特課:

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

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

這是我的組件代碼:

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

}

這是我實現分頁的模板部分:

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

有人可以幫助我提前發現我的“可觀察的感謝”嗎

因為getPageClient功能是異步的, pageClient是當第一次加載頁面不確定的。 這意味着在執行pageClient.content ,您將得到一個錯誤。

幸運的是,Angular提供了一些有用的語法,您可以在模板中使用以避免這種情況。 您應該改用*ngIf="pageClient?.content" >

? 告訴Angular僅在pageClient不為null / undefined時讀取content

更多信息在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM