0

Imagine you have a global "execution context" service for logging (comparable to MDC) and two kinds of triggers like user interaction and web socket connection.

We have a logger service, which uses the "execution context" for log messages.

The user press on a button, the service gets the context, a http request will be triggered and the result interpreted including logging.

Meanwhile we receive a message over the websocket and needs to interpret it as well. So we set our "execution context" and overwrite the existing one in the services.

The issue will be that the log messages will get the same execution context if the websocket observable will be triggered before the http result is received.

Is there any possibility to have own execution context for multiple observables?
I was thinking about using the NgZone (zone.js) for this, but I don't find any method for storing a context.

CSchulz
  • 10,882
  • 11
  • 60
  • 114

1 Answers1

0

you can use zone.js to do that. you need to create your own zoneSpec to store your own context object. in your button click event handler.

<button (click)="clicked()">Click</button>

clicked() {
  Zone.current.fork({
    name: 'context',
    properties: {
      context: YOUR_OWN_CONTEXT_OBJECT
    }
  }).run(()=> {
    yourService.getData().subscribe(data => {
      // you can access the context like this.
      const context = Zone.current.get('context');
    });
    webSocket.on('message', function(data) {
      // you can access the context like this.
      const context = Zone.current.get('context');
    });
  });
}

here is the plunker, I am not sure what is your requirement, the plunker just show how to share data. https://plnkr.co/edit/xHZbs1Zb04CbM73ydSYR?p=preview

jiali passion
  • 1,691
  • 1
  • 14
  • 19