3

当我使用httpClient调用我的 Web 服务时,我开始在我的 Angular 服务中使用 Spring Rest 和 Angular 5 实现一个简单的分页,并通过请求的页面获得正确的响应,它在我的页面上正确显示数据,但控制台 Web 出现错误浏览器在我的*ngFor循环中出现错误无法读取未定义的属性,尽管模板显示结果正确:

问题出在 Service 方法中:getPageClient() 和 *ngFor 指令这是我的错误日志: 在此处输入图像描述

这是我使用 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);
    };
  }
}

这是我的模型类:

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>

有人可以帮我提前找到我的 ObservableThanks 的问题吗

4

1 回答 1

5

因为该getPageClient函数是异步的,pageClient所以在页面首次加载时未定义。这意味着当你做的时候pageClient.content,你会得到一个错误。

值得庆幸的是,Angular 提供了一些有用的语法,您可以在模板中使用来避免这种情况。你应该*ngIf="pageClient?.content" >改用。

?告诉 Angular 仅在不为空 / 未定义content时才读取。pageClient

更多信息在这里

于 2018-07-07T23:28:14.500 回答