组件如何订阅由其他组件触发的http.get?

时间:2017-08-04 08:27:12

标签: angular

我想从http.get订阅observable而不触发它,因为我希望它由其他一些组件触发。

目前,我这样做:

shared.service.ts

    getAllIcons(){
        console.log('getting all icons');
        return this.http.get(`http://localhost:3000/AllIcons`).map(function (response: Response) {
          return response.json();
        })
    }

component1

this.sharedService.getAllIcons().subscribe(
      (value) =>{console.log(value);});
  }

<小时/> 我想要实现的目标

shared.service.ts

  _observableForAllImages: Observable<{}>;
    getAllIcons(){
        console.log('getting all icons');
        return _observableForAllImages =  this.http.get(`http://localhost:3000/AllIcons`).map(function (response: Response) {
          return response.json();
        })
    }

COMPONENT2

this.sharedService.getAllIcons().subscribe(
      (value) =>{console.log(value);});
  }

COMPONENT1

//BUT THIS GIVES ERROR
    this.sharedService._observableForAllImages.subscribe((value)=>{
          console.log(value);
         this.imageContainers = value.imageContainers;
        });
**ERROR =  TypeError: Cannot read property 'subscribe' of undefined**

我为什么要这样做?

我有一个名为imageGridComponent的组件。该组件由各种父组件使用路由调用,而imageGridComponent显示与该父组件对应的所有图像。因此,我希望parent是触发组件,child是使用组件的数据。

编辑:我的问题不是将http调用的结果分享给各种订阅。而是关于从服务方法接收数据的单个订阅(在子组件中)将由不同的父母调用。我附上了一个原理图来解释它。

enter image description here

0 个答案:

没有答案