将订阅转换为对象

时间:2016-08-04 10:13:29

标签: typescript angular mapping observable subscribe

我从网络服务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);
}

问题在于我想在其他方法中使用医生列表,例如通过Key获取医生或获取医生名单......,我创建了这种方法:

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

但问题是医生名单未定义,它没有映射到对象Doctor,请我需要一些帮助!!!!!

1 个答案:

答案 0 :(得分: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 :更改getdoctorsById

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

即。删除作业。