Using BokehJS in an Angular app

Okay, I did not give up, and finally got this to work. If anyone else is interested, here is what I did. The main trick was to import just the required file from the build subdirectory.

In the Python script

import json
from bokeh.embed import json_item
from bokeh.plotting import figure, output_file

p = figure()
p.circle([1], [1])
with(open("simple_plot.json", 'w')) as f:
    f.write(json.dumps(json_item(p)))
print("done")

In my angular component

In the TypeScript file :

import * as Bokeh from '@bokeh/bokehjs/build/js/lib/embed';

...

let bokehJson = ....retrieve the JSON file content generated by Python...
Bokeh.embed_item(JSON.parse(bokehJson), "bokeh-div-id");

In the HTML template file:

<div id="bokeh-div-id"></div>

This should be sufficient for most uses. However I wanted to use a more complex Bokeh plot with widgets and tables: those must be imported manually, and only once to prevent multiple declarations warnings. So:

In the angular application file main.ts

import * as Widgets from '@bokeh/bokehjs/build/js/lib/models/widgets/index';
import * as Tables from '@bokeh/bokehjs/build/js/lib/models/widgets/tables/index';
import { register_models } from "@bokeh/bokehjs/build/js/lib/base";

...

    register_models(Widgets);
    register_models(Tables);

And with this, you should be good to go !

1 Like