代码之家  ›  专栏  ›  技术社区  ›  Matthew Flynn

利用角模态廊道的异步管道

  •  0
  • Matthew Flynn  · 技术社区  · 7 年前

    我想用 angular-modal-gallery 插件,用于显示从JSON服务返回的URL中的多个图像。

    如果我对演示进行硬编码,模式库就可以正常工作。但是,当我尝试加入我的服务时,它就停止工作了。

    在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时,会得到以下错误:

    错误类型错误:无法读取空的属性“length” 在modalgallerycomponent.initmimages

    我还尝试修改以下内容以返回 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>
    

    然后我得到以下错误:

    错误类型错误:无法读取未定义的“get”属性 在catchsubscriber.baseservice.handleError[作为选择器]

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sachila Ranawaka    7 年前

    不要订阅服务。 async Pipe会帮你的。将返回的Observable分配给 myModalImages 属性。

    constructor(private galleryService: GalleryService, private imageService: ImageService) {
    
        this.myModalImages= this.imageService.getModalImages() ;
    }
    
    推荐文章