我正在尝试使用angular-modal-gallery
插件来显示从服务返回的json中的大量图像。
如果我按照演示进行硬编码,则模态画廊效果很好。但是,当我尝试连接我的服务时,它将停止工作。
在我的component.html中;
<ks-modal-gallery [id]="1" [modalImages]="myModalImages | async"></ks-modal-gallery>
然后在component.ts;
myModalImages: Image[];
myModalImagesSubscription: Subscription;
constructor(private galleryService: GalleryService, private imageService: ImageService) {
this.myModalImagesSubscription = this.imageService.getModalImages().subscribe((result: Image[]) => {
this.myModalImages = result;
});
}
getModalImages()
在哪里;
getModalImages(): Observable<Image[]> {
return this.http.get(environment.apiUrl + "/image/portfolio/modal/", this.buildRequestOptions())
.map(res => res.json())
.catch(this.handleError);
}
现在api被命中,并且Json返回结果。但是,当我运行SPA时,出现以下错误;
错误TypeError:无法读取null的属性“ length” 在ModalGalleryComponent.initImages
我还尝试了以下修改,以返回Observable
对象;
myModalImages: Observable<Image[]>;
constructor(private galleryService: GalleryService, private imageService: ImageService) {
this.myModalImages = this.imageService.getModalImages();
}
哪个建议在获取图像之前尝试初始化?
有人可以指导我,并告诉我我在做什么错吗?
最后,我尝试按照以下步骤删除async
管道并初始化数组;
myModalImages: Image[] = [];
myModalImagesSubscription: Subscription;
constructor(private galleryService: GalleryService, private imageService: ImageService) {
this.myModalImagesSubscription = this.imageService.getModalImages().subscribe((result: Image[]) => {
this.myModalImages = result;
});
}
在html中带有以下内容;
<ks-modal-gallery [id]="1" [modalImages]="myModalImages"></ks-modal-gallery>
然后出现以下错误;
错误TypeError:无法读取未定义的属性“ get” 在CatchSubscriber.BaseService.handleError [作为选择器]
答案 0 :(得分:1)
不订阅该服务。 async
管道将为您做到这一点。将返回的可观察值分配给myModalImages
属性。
constructor(private galleryService: GalleryService, private imageService: ImageService) {
this.myModalImages= this.imageService.getModalImages() ;
}