多个模块的通用服务

时间:2019-01-04 13:28:29

标签: angular rxjs observable

有人可以帮我解决此问题吗? 我有一个具有多种方法的服务,每种方法从服务器接收到响应后都会执行某些任务,然后必须将修改后的响应传递给相应的调用者组件。 这是我在服务中使用的代码。

 getData(observer){
          // prepare request Object
         this.httpService.getDropdownData(reqObj).subscribe(
                (data) => {

                 // modify response and then pass it to the respective component.
                  //I can't think of any solution from here. tried adding 
                   observable  but  not getting the desired output(scoping issue)


                 observer.next(data);
                 observer.complete();  
                }, (error) => {
                   // error case
            });
      }

    public observeData = new Observable(getData);


    // component code.

    this.cmpService.observeData().subscribe( response){
        do something with the response.
    };

expecting a modified output in each component.

2 个答案:

答案 0 :(得分:0)

最好是这样的:

服务

getData(): Observable<any> {
  return this.httpService.getDropdownData(reqObj).pipe(
    // do your stuffs here with the help of rxjs operators
  );
}

组件:

this.cmpService.getData().subscribe(
  data => console.log(data), // here you'll get modified datas
  err => console.log(err),   // here, you'll manage errors in your component
  () => {}
);

希望对您有所帮助;-)

答案 1 :(得分:0)

这是我尝试并能够实现的目标,但不确定是否会对性能产生影响,以及这是否是使用可观察的正确方法?

pubEndpoint := "tcp://127.0.0.1:7000"
pubSock, err := goczmq.NewPub(pubEndpoint)
if err != nil {
    log.Fatal(err)
}
defer pubSock.Destroy()
pubSock.Bind(pubEndpoint)

for {
    err = pubSock.SendFrame([]byte("stream hello"), goczmq.FlagNone)
}

//组件代码。

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://127.0.0.1:%s"%port)
print ('port:',port)
socket.setsockopt(zmq.SUBSCRIBE, "stream")

while True:
    transpport = socket.recv()
    transpport = transpport.split('stream ')[1]
    print (transpport)