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

问题描述 投票:0回答:3

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

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"
}

人,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);
  }
}
angular
3个回答
2
投票

当你异步地抓住这些人时。因此,您必须使用* ngIf检查天气是否有人物对象。原因正如您的DOM渲染时间“人”当时不可用。

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

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


1
投票

有两种方法可以解决此错误。第一种方法 - >初始化人

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

第二种方法检查人的未定义值,直到得到一个值。

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

希望这会有所帮助。


-1
投票

你应该告诉angular将使用html中的这种表示法来处理这些数据

只是使用[value] =“object.property”

© www.soinside.com 2019 - 2024. All rights reserved.