【问题标题】:ERROR Error: Uncaught (in promise): TypeError: Unable to get property 'Results' of undefined or null reference错误错误:未捕获(承诺中):TypeError:无法获取未定义或空引用的属性“结果”
【发布时间】:2017-11-14 10:46:26
【问题描述】:

我收到以下错误。我正在发布我的代码的所有内容。请查看下面的所有代码。谢谢

错误错误:未捕获(承诺中):TypeError:无法获取未定义或空引用的属性“结果” TypeError:无法获取未定义或空引用的属性“结果” 在匿名函数(函数代码:492:5) }

HTML

<div class="row">  
   <table class="table table-striped table-hover col-md-12 col-sm-12">
        <thead>
            <tr>
                <th>Title</th>
                <th>Submitting Department</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <tr *ngFor="let event of filterdResult.Results">
            <td>{{ event.Title }}</td>
            <td>{{ event.SubmittingDepartment }}</td>
            <td>{{ event.StartDateTime }}</td>
            <td>{{ event.EndDateTime }}</td>
            <td>
                <a [routerLink]="['/event', event.HealthFairEventId]">
                    <i class="glyphicon glyphicon-edit"></i>
                </a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

组件

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { SearchParameters, PagedResults } from '../event.model';
import { EventService } from '../event.service';

@Component({
  selector: 'app-events-list',
  templateUrl: './events-list.component.html',
  styleUrls: ['./events-list.component.css'],
  providers: [EventService]
})
export class EventsListComponent implements OnInit {
  filterdResult: PagedResults;
  searchparameters: SearchParameters = new SearchParameters();

  constructor(private eventService: EventService,
              private route: ActivatedRoute) {     
  }

  ngOnInit() {
    this.searchparameters.SortField = "Title";
    this.searchparameters.SortDirection = "ASC";
    this.searchparameters.PageSize = 10;
    this.searchparameters.CurrentPageIndex = 1;

    this.eventService.getEvents(this.searchparameters)
                    .subscribe(  
                      //filterdResult => console.log(filterdResult),
                      filterdResult => this.filterdResult = filterdResult,
                      response => {
                        console.log('error occured');
                      });
  }

}

服务

import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import 'rxjs/add/operator/map';

import { Event, SearchParameters } from './event.model';

@Injectable()
export class EventService {    
    private _url = "http://localhost:36888/api/XX";

    constructor(private _http: Http) {
    }

    getEvents(SearchParameters) {        
        return this._http.post(this._url + "/XX", SearchParameters).map(res => res.json());
    }

   }

模型类

export class Event {
    HealthFairEventId: number;
    Title: string
    SubmittingDepartment: string;
    Location: string;
    Description: string;
    StartDateTime: Date;
    EndDateTime: Date;  
    RecommendedParticipantsInvitationValues: participants[];
    RecommendedParticipantsValues: boolean[];
    /*constructor(healthFairEventId: number, title: string, submittingDepartment: string, location: string, startDateTime: string, endDateTime: string, description: string) {
        this.healthFairEventId = healthFairEventId;
        this.title = title;
        this.submittingDepartment = submittingDepartment;
        this.location = location;
        this.startDateTime = startDateTime;
        this.endDateTime = endDateTime;
        this.description = description;
    }*/
}

export class participants {
    RecommendedParticipantId: number;
    DepartmentName: string;
    DepartmentLocation: string;
    ContactPersonName: string;
    ContactPersonEmail: string;
    ContactPersonPhone: string;
    RecommendedParticipantsIsChecked: boolean;
    InvitationStatus?: boolean;
    InvitationStatusCSSClass: string;
    InvitationStatusText: string;
}

export class SearchParameters {
    Title: string;
    EventDateFrom: string;
    EventDateTo: string;
    Location: string;
    SubmittingDepartment: string;
    SortField: string;
    SortDirection: string;
    PageSize: number;
    CurrentPageIndex: number;
}

export class PagedResults {
    PageNumber: number;
    PageSize: number;
    TotalNumberOfPages: number;
    TotalNumberOfRecords: number;
    Results: Event[];
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    当模板首次显示时,此处使用的 filterdResult let event of filterdResult.Results 尚未设置。因此它告诉您它无法从 undefined 获取结果的原因。

    在 html 周围(可能在 table 元素上)添加一个 *ngIf 以防止它在设置 filterdResult 之前显示:

    <table *ngIf = "filterdResult" ...>
    

    【讨论】:

      【解决方案2】:

      您收到错误是因为最初呈现页面时filterdResultundefined。直到 webservice 调用解决,filterdResult 才会最终获得一个值,并且页面会按照您的意愿呈现。

      两种解决方案

      选项 1
      在表格标记中添加*ngIf,以便在filterdResult 具有如下值之前不会呈现表格:

      &lt;table *ngIf="filterdResult" class="table table-striped table-hover col-md-12 col-sm-12"&gt;

      选项 2
      filterdResult初始化为这样的初始值

      export class EventsListComponent implements OnInit {
        filterdResult: PagedResults = new PagedResults();
        // or like below if PagedResults is an interface
        // filterdResult: PagedResults = {Results: []};
      

      【讨论】:

        猜你喜欢
        • 2021-04-18
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-01
        • 1970-01-01
        • 2018-06-11
        • 2019-06-19
        相关资源
        最近更新 更多