Angular2 Interfacing with External JS E.g. PouchDB

Introduction

This blog demonstrates how to interface Angular2 TypeScript with JavaScript.

PouchDB is used as an example JavaScript library.

How to setup a PouchDB in JavaScript

How to setup PouchDB in general is simple as explained here: https://pouchdb.com/

Add PouchDB to index.html

<script src="https://cdn.jsdelivr.net/pouchdb/6.0.5/pouchdb.min.js"></script>

This one line of code sets up a database called “dbName”;

var db = new PouchDB('dbname');

Simple as that, now it’s possible to call db.put(), db.post(''') db.addDocs()  etc.

Diving Straight into TypeScript and PouchDB

Add PouchDB to your application

As with a traditional JavaScript application, add the script to index.html

<script src="https://cdn.jsdelivr.net/pouchdb/6.0.5/pouchdb.min.js"></script>

Service

As per the example service below,

  • Declare the PouchDB variable. This is the JavaScript variable name. This imports the JavaScript object into the TypeScript domain.
    • The name PouchDB must match the JavaScript object name.
    • This allows an instance to be new’ed up with new PouchDB(“dbname”);
  • Create an instance vrariable to work with.
  • Initialise the instance variable in the constructor.
  • Then add relevant functions….

 

Note that list and save both return PouchDB promises.

Get Stuff

Use the service as so

 

Note how the getStuff function receives a PouchDB promise from the service. This of course has nothing to do with Angular2 or TypeScrtipt, it’s simply that all operations in PouchDB are asynchronous.

Add Stuff

Adding a new “Stuff” item looks like this

 

Conclusion

Keeping things succinct, interfacing external JavaScript libraries from Angular2 TypeScript has been demonstrated using PouchDB as an example.

It’s a matter of:

  • Including the relevant JavaScript library
  • Declaring the JavaScript object within TypeScript
  • Then it’s ready to use.

Comments always welcome…

1 Comment