无法读取属性' FirstName'角度不确定的

时间:2018-06-04 07:36:05

标签: angular

在显示时,它显示人口统计数据为FirstName = Vinit但同时显示错误,因为无法读取属性' FirstName'未定义的 请帮我解决这个错误。告诉我为什么会发生这个错误。谢谢。

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

1 个答案:

答案 0 :(得分:2)

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