错误TypeError:无法读取person.component.html中未定义的属性“ FirstName”

时间:2018-10-01 14:54:44

标签: angular

我尝试了多种显示名字的方法,但是每次遇到这个错误时,我都不知道我在哪里没有定义这个名字。有人可以解释这个错误的确切含义吗?请帮助我,并给我适当的解释,以便将来不要忘记此错误解决方案。

person.component.html

 <div class="ui-inputgroup">
   <input type="text" size="30"  name="something" value="{{ persons.FirstName }}" pInputText>      
</div>

person.component.ts

   import { Component, OnInit } from '@angular/core';
    import { CountryService} from './country-list.service';
    import {SelectItem} from 'primeng/api';
    import { Message } from 'primeng/components/common/api';
    import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
    import { PersonListService,Person} from './person-list.service';
    import { DatePipe } from '@angular/common';

    @Component({ 
      moduleId: module.id,
      selector: 'sd-person',
      templateUrl: 'person.component.html',
      providers:[DatePipe],
      styleUrls: ['person.component.css']
    })
    export class PersonComponent implements OnInit {

    persons: Person;
      date3:Date;
      dates: Date[];
      rangeDates: Date[];
      minDate: Date;
      maxDate: Date;
      es: any;
      invalidDates: Array<Date>
      val2: string = 'Male';
      val3: string = 'Unmarried';
      text: string;
      ValidIds: SelectItem[];
      selectedvalidid2: string = '';
      Religions: SelectItem[];
      selectedvalidid3: string = '';
      BloodGroups: SelectItem[];
      selectedvalidid4: string = '';
      Martials: SelectItem[];
      selectedvalidid5: string;
      country: any;
      filteredCountriesSingle: any[];
      msgs: Message[] = [];
      userform: FormGroup;
      submitted: boolean;
    name:string;

      constructor(private countryService: CountryService,private fb: FormBuilder,public personListService:PersonListService,private datePipe: DatePipe) { }

      filterCountrySingle(event) {
          let query = event.query;
          this.countryService.getCountries().then(countries => {
              this.filteredCountriesSingle = this.filterCountry(query, countries);
          });
      }

      filterCountry(query, countries: any[]):any[] {
        //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
        let filtered : any[] = [];
        for(let i = 0; i < countries.length; i++) {
            let country = countries[i];
            if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
                filtered.push(country);
            }
        }
        return filtered;
    }
      ngOnInit() {

        this.getperson();
    }
        getperson(){

            this.personListService.getPersonalInformation()

            .subscribe(
             resp =>{
             this.persons = resp.Persons;

 this.date3 = new Date(this.persons.Birthdate)
              this.selectedvalidid5=this.persons.MartialStatus
             this.val2=this.persons.Gender
             this.selectedvalidid2=this.persons.ValidIdType
             this.selectedvalidid3=this.persons.Religion
             this.selectedvalidid4=this.persons.BloodGroup
        });     
       }
        onSubmit(value: string) {
            this.submitted = true;
            this.msgs = [];
            this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
        }
    }      

person.json

{
    "PersonId": 1,
    "FirstName": "Vinit"
}

person-list.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

export class Address{
  AddressId:number;
  AddressType:string="";
  AddressL1:string=""; 
  AddressL2:string="";
  Locality:string="";
  City:string=""; 
  State:string="";
  Country:string="";
  Postalcode:number;
}

export class Email{
  EmailNumber:number;
  EmailType:string="";
  EmailId:string="";
}

export class ContactNumber{
   ContactId:number;
   ContactType:string="";
   CountryCode:string="";
   RegionCode:string="";
   Number:number;
}

export class Skill{
  SkillId:string="";
  SkillName:string="";
  Proficiency:string="";
}

export class Activity{
  ActivitiyId:number;
  Activitiesandsocieties:string="";
  Proficiency:string="";
}

export class EducationDegree{

  EducationId:number;
  InstituteName:string="";
  EducationType:string="";
  Degree:string="";
  University:string="";
  MarksObtain:number;
  OutOf:number;
  Percentage:number;
  PassingYear:Date;
  Stream:string="";
  Grade:string="";
  CourseDuration:number;
  StartDate:Date;
  ExpectedEndDate:Date;
  ActualEndDate:Date;
}

export class Experince{

  ExperienceId:number;
    Title:string="";
    ExperienceType:string="";
    FromDate:Date;
    TodaysDate:Date;
    Renumeration:string="";
    OraganizationId:number;
    OrganizationName:string="";
    Location:string="";
}

export class Profile{

  OraganizationId:number;
  Title:string="";
  ProfileType:string="";
  FromDate:Date;
  TodaysDate:Date;
  CustomerName:string="";
  Location:string="";
}

export class Role{
  RoleId:number;
  RoleName:string="";
}

export class RoleResponsibility{

  ResponsibilityId:number;
  Responsibility:string="";
  Description:string="";
}


export class Certification{
      CertificationId:number;
      CertificationName:string="";
      CertificationAuthority:string="";
      LicenseNumber:string="";
      FromDate:Date;
      TodaysDate:Date;
      CertificationURL:string="";
}

export class Course{
      CourseId:number;
      CourseType:string=""; 
      CourseName:string="";
      StartDate:Date;
      ExpectedEndDate:Date;
      ActualEndDate:Date;
      AssociatedWith:string="";
      GradeObtain:string="";
      PercentageMarks:number; 
}

export class HonorAward{
  HonorsawardId:number;
  Title:string="";
  AssociatedWith:string="";
  Issuer:string="";
  Date:Date;
  Description:string="";
}

export class Language{
  LanguageId:number;
  Language:string="";
  Proficiency:string="";

}

export class Patent{
      PatentId:number;
      PatentTitle:string="";
       PatentOffice:string="";
       PatentorApplicationNumber:number;
       Inventor:string="";
       Status:string="";
       FilingDate:Date;
       PatentURL:string="";
       Description:string="";
}

export class Publication{
  PublicationId:number;
  PaperTitle:string="";
  PublicationorPublisher:string="";
  PublicationDate:Date;
  PublicationURL:string="";
  PaperDescription:string="";
}

export class Person{

  ProfileId:number;
  FirstName:string="0";
  LastName:string="";
  Birthdate:string="";
  MartialStatus:string="";
  Gender:string="";
  Height:string="";
  ValidIdType:string="";
  ValidIdNumber:string="";
  Nationality:string="";
  Religion:string="";
  BloodGroup:string="";
  NearestRailwayStation:string="";

  Addresses:Address[];

  Emails:Email[];

  ContactNumbers:ContactNumber[];

  Skills:Skill[];

  Activities:Activity[];

  EducationDegrees:EducationDegree[];

  Experinces:Experince[];

  Profile:Profile[];

  Roles:Role[];

  RoleResponsibilities:RoleResponsibility[];

  Certifications:Certification [];

  Courses:Course[];

  HonorAwards:HonorAward [];

  Languages:Language [];

  Patents:Patent[];

  Publications:Publication [];

  }

/**
 * This class provides the NameList service with methods to read names and add names.
 */
@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.
   */
  getPersonalInformation(): Observable<{Persons: Person }>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getSkill(): Observable<{Skills: Skill[]}>{
    console.log("Inside the get service")                                                           
    return this.http.get('app/form/person.json')

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

  }
  getActivity(): Observable<{Activities: Activity[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getAddress(): Observable<{Addresses: Address[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getEmail(): Observable<{Emails: Email[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getContact(): Observable<{ContactNumbers: ContactNumber[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getEducation(): Observable<{EducationDegrees: EducationDegree[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getExperienceDetail(): Observable<{Experieces:Experince[] }>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getProfileDetail(): Observable<{Profile:Profile[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getRole(): Observable<{Roles:Role[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getResponsibilites(): Observable<{RoleResponsibilities:RoleResponsibility[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getCertification(): Observable<{ Certifications: Certification[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getCourse(): Observable<{ Courses: Course[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getHonoraward(): Observable<{ HonorAwards: HonorAward[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getLanguage(): Observable<{ Languages: Language[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }
  getPatent(): Observable<{ Patents: Patent[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  getPublication(): Observable<{ Publications: Publication[]}>{
    console.log("Inside the get service")
    return this.http.get('app/form/person.json')

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

  }

  /**
    * Handle HTTP error
    */
  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);
  }
}

3 个答案:

答案 0 :(得分:2)

当您异步获取人员时。因此,您必须使用 * ngIf 检查天气Person对象是否可用。原因由于您的DOM渲染“人物”的时间当时不可用。

<div class="ui-inputgroup" *ngIf="persons">
   <input type="text" size="30"  name="something" value="{{ persons.FirstName }}" pInputText>      
</div> 

在此之前,请在控制台中打印“ this.persons” 值。您是否从json获得价值。

答案 1 :(得分:1)

有2种方法可以修复此错误。 第一种方法->初始化人

persons: Person = {
    "PersonId": 0,
    "FirstName": ""
}

第二种方法检查人员的未定义值,直到获得值为止。

 <div class="ui-inputgroup">
   <input type="text" size="30"  name="something" value="{{ persons?.FirstName }}" pInputText>      
</div>

希望这会有所帮助。

答案 2 :(得分:-1)

您应该告诉Angular将使用html中的这种表示法处理此数据

           

仅使用[value] =“ object.property”