0

On display, it is showing demographics data as FirstName=Vinit but at the same time, it is giving error as Cannot read property 'FirstName' of undefined please help me to solve this error. Tell me why this error occurred.Thanks a lot.

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

1 Answer 1

2

Do {{demographics?.FirstName }}. Since demographics is loaded asynchronously, you should use safe navigation operator (?.).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.