2016-08-04 161 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

答案已更新 –