당신은 당신이 요소가 포함되어 있는지 확인하고없는 경우 빈 배열을 반환해야 this.doctors
액세스 할 때마다 :
getdoctorsById():Doctor[] {
if (!this.doctors.length)
return [];
return (this.doctors = this.doctors.filter(doctor => doctor.id === this.id));
}
업데이트 : 내가 문제를 볼 생각합니다. 이 같은 doctors
의 배열을 선언하려고 : 이로써
doctors:Doctor[] = [];
당신이 빈 상태 (empty)의 배열에 의해이 배열을 초기화합니다.
갱신 2 : 같은 방식으로 이전과 당신의 DoctorService
(파일 NestedJson.service.ts
)를 선언하고 액세스 this.doctors
에서
:
이
doctors:Doctor[];
...
function toDoctor(r:any):Doctor{
let doctor = <Doctor>({
id:r.id,
name:r.name,
username:r.username,
email:r.email,
phone:r.phone,
website:r.website,
company:r.company,
address:r.address,
});
console.log('Parsed doctor:', doctor);
this.doctors.push(doctor); // <== this.doctors === undefined here
console.log('MMMMMMMMMMMMM',this.doctors);
return doctor;
}
그래서, 빈 배열로에게 같은 초기화
업데이트 3 : 변경 getdoctorsById
:
getdoctorsById():Doctor[]{
return this.doctors.filter(doctor => doctor.id === this.id);
}
. 할당을 제거하십시오.
구독이 비동기 적으로 작동합니다. 'getdoctorsById' 함수를 호출 할 때 의사에 대한 http 요청이 끝났다고 보장 할 수 없습니다. – Matt
그래서 어떻게해야합니까? –
getdoctorsById() 함수를 호출하는 곳을 게시 할 수 있습니까? – Matt