Angular 2 Observables数据格式如何与Interface匹配

Angular 2 How to match Observables data format with Interface

基本上问题就是如何把observable返回的格式改成接口格式。我的意思是,当我从数据库中获取数据时,它的格式为:id, name, img_path, description。但是我想将结果分配给接口:

export interface IGallery {
    id: number;
    thumb: string;
    img: string;
    description? : string;
}

当我使用我的服务时:

images:IGallery[];

this._dataService.getEventGallery()
    .subscribe(

      images => { 

        //images 
        this.images = images; <-- how to convert to interface here
        console.log(this.images);
      },
      err => {
        console.log(err);
      }
    );

为了使用*ngFor 显示这些图像。

目前我是这样解决的,但这不是最好的解决方案:

.subscribe(

          images => { 

            let result = images;
            let finalArray = [];

            for (var i = 0; i < result.length; i++) {

              console.log(result[i]);
              finalArray.push({thumb: "assets/img/1/events/" + result[i].img_path, img: "assets/img/1/events/" + result[i].img_path, description: result[i].description});
            }

            this.images = finalArray;
            console.log(this.images);


          },
          err => {
            console.log(err);
          }
        );

这就是为什么我们有 map operator

这应该可以解决问题(假设 getEventGallery() returns 一个数组,您的代码似乎表明它确实如此):

images:IGallery[];

this._dataService
    .getEventGallery()
    .map((images) => {
        return images.map((image) => {
            return {
                thumb: "assets/img/1/events/" + image.img_path,
                img: "assets/img/1/events/" + image.img_path,
                description: image.description
            };            
        });
    })
    .subscribe(

      images => { 

        //images 
        this.images = images;
        console.log(this.images);
      },
      err => {
        console.log(err);
      }
    );

使用地图运算符。

this._dataService.getEventGallery()
.map(images=>images.map(image=>{thumb: "assets/img/1/events/" + image.img_path, img: "assets/img/1/events/" + image.img_path, description: image.description}))
.subscribe(
  images => { 
    this.images = images;
    console.log(this.images);
  },
  err => {
    console.log(err);
  }
);