2016-08-04 162 views
0

我收到來自Web服務Doctor.service.ts數據:轉換訂閱對象

*getAllDoctors():Observable<Doctor[]>{ 
let doctor$ = this.http 
    .get(`${this.baseUrl}/users`,{headers: this.getHeaders()}) 
    .map(mapDoctor) 
    return doctor$;} 



*function mapDoctor(response:Response):Doctor[]{ 
return response.json().map(toDoctor);} 




*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); 
return doctor; 
} 

在component.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[] = []; 

通過這個,你通過一個空數組初始化數組。

UPDATE2

在你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; 
} 

所以,初始化它同樣具有空數組

Update3:Change getdoctorsById

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

I.e.刪除分配。

+0

問題是我不能使用像醫生對象 –

+0

這樣的醫生在索引訪問元素之前,您總是必須檢查數組中是否有項。但是,如果你在* t​​emplate *中使用這個空數組,'ngFor'將不會執行,因爲沒有元素。 –

+0

答案已更新 –