角5-可观察到的返回错误无法读取未定义的属性 [英] Angular 5 - Observable return error cannot read property of undefined

查看:80
本文介绍了角5-可观察到的返回错误无法读取未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



问题出在Service方法中:getPageClient()和* ngFor指令
这是我的错误日志:



这是我使用可观察对象的服务:

  import {可注入}来自'@ angular / core'; 
从'../models/Client'导入{Client}
从{../models/PageClient'导入{PageClient}
{rxjs'从}导入{
从 @ angular / common / http导入{HttpClient,HttpHeaders};
从 rxjs / operators导入{catchError,map,tap};

@ Injectable({
includedIn:'root'
})
导出类ClientService {

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

私人urlPage =‘http:// localhost:8099 / api / clients / get?page = 0& size = 3’;

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

getPageClient():Observable< PageClient> {
返回this.http.get< PageClient>(this.urlPage)
.pipe(
map(response => {
const data = response;
console.log(data.content);
return data;
}))
}
构造函数(私有http:HttpClient){}

private handleError< T> (运算=运算,结果?:T){
return(错误:任何):Observable< T> => {

// TODO:将错误发送到远程日志记录基础结构
console.error(error); //登录到控制台,而不是

// TODO:更好地转换错误以减少用户消耗
console.log(`$ {operation}失败:$ {error.message}`);

//通过返回空结果让应用程序继续运行。
的回报(结果为T);
};
}
}

这是我的模型课程:

 从'../models/Client'导入{Client}; 

导出类PageClient {
content:Client [];
totalPages:数量;
totalElements:数字;
last:布尔值;
大小:number;
首先:布尔值;
sort:字符串;
numberOfElements:number;
}

这是我的组件代码:

 从'@ angular / core'导入{Component,OnInit}; 
从‘../models/Client’导入{Client};
从 ../models/PageClient导入{PageClient};
从 ../services/client.service导入{ClientService};

@Component({
选择器:'app-clients',
templateUrl:'./clients.component.html',
styleUrls:['./ client.component.css']
})
导出类ClientsComponent实现OnInit {

客户:Client [];
pageClient:PageClient;

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

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

}
构造函数(私有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>上一页< / a>
< / li>
< li * ngFor = pageClient.content的页面;让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>(当前)< / span>< / a>
< / li>->
< li class = page-item>
< a class = page-link href =#> Next< / a>
< / li>
< / ul>
< / nav>

有人可以帮我找到我的Observable
问题吗?

解决方案

由于 getPageClient 函数是异步的,因此 pageClient 是未定义的。这意味着当执行 pageClient.content 时,会出现错误。



感谢Angular提供了一些有用的您可以在模板中使用的语法来避免这种情况。您应该改用 * ngIf = pageClient?.content>



告诉Angular仅读取 content ,如果 pageClient 不为null或未定义。 / p>

此处更多信息


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 :

The problem is in the Service method : getPageClient() and the *ngFor directive This the log of my error :

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. That means when doing pageClient.content, you will get an error.

Thankfully, Angular provides a useful bit of syntax you can use in the template to avoid this. You should use *ngIf="pageClient?.content" > instead.

The ? tells Angular to only read content if pageClient is not null / undefined.

More info here

这篇关于角5-可观察到的返回错误无法读取未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆