Angular & Bokeh combined with a Python Backend...
Tags: python, bokeh, angular, dashboard
Published: 2020-07-11 09:10:16

If you want to be able to send update events from the python back-end and have all the nice interactions like button press- and text input- events coming with Angular, you might like this first example on the usage:

This angular-project is located at: <https://github.com/NuCOS/angular-bokeh>.

From here you can implement your interactions,
we wanted to keep this example as clean as possible, that is why we did not over-float the example with stuff that actually is not in a direct connection with the basic-problem described above.

To integrate the BokehJS lib into an Angular project we use an angular component named **bokeh-chart**. The plotting data is most likely provided by a websocket service, in our example, we use **aiohttp**, but you are free to set up any other websocket connection.
The angular component may be integrated anywhere in the html by its tag-name, the following snippet shows the Bokeh chart component

``` typescript
<bokeh-chart></bokeh-chart>
```

The **bokeh-chart** component is a regular angular component,  with a html part

``` html
<div [id]="id"></div>
```

and a typescript part. The chart component only needs to provide the **id** to its own html part. The data for the chart is provided by a service that is called right at the initialization of the component in **ngOnInit**. The relevant typescript part of the Bokeh chart component looks like this:

``` typescript
...
export class BokehChartComponent implements OnInit {
  public id: string;

  constructor(
    private bokehService: BokehService) { }


 ngOnInit() {
     this.id = "chart";
     this.bokehService.getChart(this.id);
 }
}
```

Since the **BokehJS** lib has no types available, the integration in angular is not as straightforward as it should be. One has access to that lib only via the global exposed object of the lib, which in this case is also named **Bokeh** and which is the only hook which is necessary to embed a chart.

``` typescript
// this is the global hook to the bokehjs lib (without types)
declare var Bokeh: any;
```

This magic works only as expected if you plug in the usual java script into the topmost html file of the angular app index.html

``` html
<head>
 ...
  <link
    href="https://cdn.bokeh.org/bokeh/release/bokeh-1.0.4.min.css"
    rel="stylesheet" type="text/css">
  <script src="https://cdn.bokeh.org/bokeh/release/bokeh-1.0.4.min.js"></script>
 </head>
```

The **BokehService** provides the data for the chart via a **MessageService** which encapsulates the connection to the backend such that one only needs to send a proper message by the exposed method **sendMsg**(msg: Message). 

``` typescript
export class BokehService extends Connector {
constructor(private msgService: MessageService) {
 super('BokehService');
 this.msgService.register(this);
 }
…
public getChart(id: string) {
 const msg = {
 name: 'addChart',
 args: [id],
 action: 'default'
 };
 this.msgService.sendMsg(msg);
 }
```

This service also exposes a method to the backend, that actually plots the chart into the native DOM-element, where we have to delete first the previous plots

``` typescript
public plot(msg: Message) {
      const id = msg.args.id;
      const el = document.getElementById(id);
      // first remove the previous charts as child
      // this is necessary, since bokeh do not let us update a chart
      while (el.hasChildNodes()) {
            el.removeChild(el.lastChild);
      }
      // be sure to include the correct dom-id as second argument
      Bokeh.embed.embed_item(msg.args.item, id);
    }
```

The back-end service in our example is written in python. As i said, we use aiohttp as an **async** solution for the web server. Right after starting the angular app in the browser, the angular **WebsocketService** connects immediately to the python backend on server side. Remember that in production you would implement more security on that point, like an authentication. The backend is ready to receive events from angular, like e.g. give me the data for the Bokeh chart.
The **addChart**, which is called by the message from angular, sends the chartItem as a json item that connects to the websocket service

``` python
async def addChart(self, id_, user):
    """
    Example for adding a bokeh chart from backend

    """
    chartItem = self.chartProvider.chartExample()
    print("try to add chart for dom-id %s" % id_)
    context = {"name": "BokehService",
               "args": {"item": chartItem, "id": id_},
               "action": "plot"}
    await self.send_event(json.dumps(context), user=user)
```

The interesting part here is the **send_event** method which in fact is based on our implementation of the websocket server. As already mentioned, that part may differ in your individual implementation.
The minimal example for the chart, also written as a member function of ChartProvider class, looks very simple and just produces the data for a plain sin-plot in Bokeh

``` python
import time
import numpy as np
from bokeh.plotting import figure
from bokeh.embed import json_item

class ChartProvider():
    def chartExample(self):
        t0 = time.time()
        # prepare some data
        self.phi += 0.02
        x = np.arange(0., 10., 0.1)
        y = np.sin(x + self.phi)
        # create a new plot
        p = figure()
        p.line(x, y, legend="SIN")
        chart_item = json_item(p)
        print(time.time()-t0)
        return chart_item
```