2016-08-04 5 views
0

내가 웹 서비스 Doctor.service.ts에서 데이터를 받고 있어요 객체에 가입변환은

doctors:Doctor[]; 

ngOnInit(){ 
this.doctorService 
    .getAllDoctors() 
    .subscribe(p => this.doctors = p); 
} 

문제는 키로 의사를 얻거나 의사 목록을 얻는 것과 같이 다른 방법으로 의사 목록을 사용하고 싶다는 것입니다.이 방법을 만들었습니다.

getdoctorsById():Doctor[]{ 
return (this.doctors = this.doctors.filter(doctor => doctor.id === this.id)); 
} 

하지만 문제는 의사 목록이 정의되어 있지 않습니다. 개체 닥터에게 매핑되지 않았습니다. 도움이 필요합니다. !!!!!

+0

구독이 비동기 적으로 작동합니다. 'getdoctorsById' 함수를 호출 할 때 의사에 대한 http 요청이 끝났다고 보장 할 수 없습니다. – Matt

+0

그래서 어떻게해야합니까? –

+0

getdoctorsById() 함수를 호출하는 곳을 게시 할 수 있습니까? – Matt

답변

0

당신은 당신이 요소가 포함되어 있는지 확인하고없는 경우 빈 배열을 반환해야 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); 
} 

. 할당을 제거하십시오.

+0

문제는 Doctor 객체와 같은 의사를 사용할 수 없다는 것입니다. –

+0

인덱스로 요소에 액세스하기 전에 배열에 항목이 있는지 항상 확인해야합니다. 그러나이 빈 배열을 * template *에 사용하면 요소가 없기 때문에'ngFor'가 실행되지 않습니다. –

+0

답변이 –