无法读取的未定义的属性“姓”中的角[复制](Cannot read property 'Fi

2019-11-04 19:35发布

这个问题已经在这里有答案 :

在显示器,它显示的人口统计数据为姓=但摄影指导Vinit在同一时间,它给误差不能读取属性“姓”的不确定,请帮我解决这个错误。 告诉我为什么这个错误occurred.Thanks很多。

人,list.service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import 'rxjs/add/operator/do';  // for debugging
export class Demographic{

  FirstName:string="";
  LastName:string="";

}
@Injectable()
export class PersonListService {

  /**
   * Creates a new NameListService with the injected HttpClient.
   * @param {HttpClient} http - The injected HttpClient.
   * @constructor
   */
  constructor(private http: HttpClient) {}

  /**
   * Returns an Observable for the HTTP GET request for the JSON resource.
   * @return {string[]} The Observable for the HTTP request.
   */
  getDemographic(): Observable<{Demographics: Demographic}>{
    console.log("Inside the get service")
    return this.http.get('app/person/person.json')

                 // .do(data => console.log('server data:', data))  // debug
                    .catch(this.handleError);

  }
private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    const errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }
}

person.component.ts

import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { PersonListService, Demographic }from './person-list.service';

@Component({
  moduleId: module.id,
  selector: 'sd-person',
  templateUrl: 'person.component.html',
  styleUrls: ['person.component.css']
})
export class PersonComponent implements OnInit {
  errorMessage: string;
demographics: Demographic;
constructor(public personListService:PersonListService){}
  ngOnInit() {
     // console.log(jwt.AuthConfig);
     this.getperson();
  }

  getperson(){

    this.personListService.getDemographic()
    .subscribe(
     resp => this.demographics = resp.Demographics,
      //resp => this.addresses = resp.Addresses,
      error => this.errorMessage = <any>error
    );
 }
 }

person.json

{
    "Demographics" : { 
            "ProfileId":1,
            "FirstName":"vinit",
            "LastName":"mapari",
            "Birthdate":"21/12/1996",
            "MartialStatus":["married","unmarried"],
            "Gender":["Male","Female"],
            "Height":"5ft2inch",
            "ValidIdTypes":["Pancard","adharcard","driving license"],
            "ValidIdNumber":"123",
            "Nationality":"Indian",
            "Religion":"Hindu",
            "BloodGroup":"A",
            "NearestRailwayStation":"byculla"

        }
}

person.component.html

<ul>
        <li><b>Demographics</b></li>
        <li>FirstName:{{ demographics.FirstName }}</li>
</ul>

Answer 1:

{{demographics?.FirstName }} 由于demographics的异步加载,你应该使用安全导航操作符(?.)



文章来源: Cannot read property 'FirstName' of undefined in angular [duplicate]