Я изучаю angular. Здесь я делаю демографический компонент как тег, и он будет использоваться лично. Он показывает мне ошибку как demographic.component.html: 3 ERROR TypeError: Невозможно прочитать свойство "FirstName" неопределенного
Если кто-то хочет его решить, я загрузил его на ссылке stackblitz ishttps://stackblitz.com/edit/ угловое-6uhfoz person.json
{
"Demographics" : {
"ProfileId":1,
"FirstName":"vinit"
}}
demographic.component.ts
import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { CardModule } from 'primeng/card';
import { ScrollPanelModule } from 'primeng/scrollpanel';
import { PersonListService,Person} from './person-list.service';@Component({
moduleId: module.id,
selector: 'sd-demographic',
templateUrl: 'demographic.component.html',
styleUrls: ['demographic.component.css']
})
export class DemographicComponent implements OnInit {
errorMessage: string;
persons: Person;
constructor(public personListService:PersonListService){}
ngOnInit() {
// console.log(jwt.AuthConfig);
this.getperson();
} getperson(){ this.personListService.getDemographic()
.subscribe(
resp => this.persons = resp.Persons, //resp => this.addresses = resp.Addresses,
error => this.errorMessage = <any>error
);
}
}
demographic.component. HTML <ul>
<li><b>Demographics</b></li>
<li>FirstName:{{ persons.FirstName }}</li>
</ul>
person.component.ts
import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { PersonListService} from './person-list.service';/**
* This class represents the lazy loaded PersonComponent.
*/
@Component({
moduleId: module.id,
selector: 'sd-person',
templateUrl: 'person.component.html',
styleUrls: ['person.component.css']
})
export class PersonComponent implements OnInit {
/*errorMessage: string;*/
constructor(public personListService:PersonListService){}
ngOnInit() {
// console.log(jwt.AuthConfig);
//this.getperson();
} }
человеко-list.service.ts
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 Person{ ProfileId:number;
FirstName:string="";
} } /**
* 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.
*/
getDemographic(): Observable<{Persons: Person}>{
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); }
person.component.html
<p-tabView>
<p-tabPanel header="Demographics"> <sd-demographic></sd-demographic> </p-tabPanel>
</p-tabView>
Когда угловые инициализируют ваш персонаж неподвижными до тех пор, пока не будут выполнены следующие действия:
Поскольку HTTP-асинхронный пользователь будет разрешен до тех пор, пока get не будет и ваш шаблон сможет его показать.
Что вам нужно сделать, так это использовать безопасный оператор или ngIf для вашего шаблона.
или