Writing Angular Services in Scala

Antoine Doeraene
12 min readJul 20, 2020

Those following my blog posts know that I like to take Scala everywhere. This time, let us write Angular services in Scala.

If you don’t know Angular, it’s a frontend web framework developed by Google in TypeScript, similar to React or Vue. It is a component based framework, and to each component is associated a TypeScript class aiming to control what the HTML component must do. These classes can use services. A service is simply another (usually global) instance of a TypeScript class, either with plenty of facility methods (for example for making http calls), or with global object used to pass information from one component to another.

Our goal today is to discover how one can create and use Angular services in Scala. Using Scala.js, we can compile our Scala code into plain old JavaScript, and export some of our classes to be used, precisely, by the JS world. Let us get started.

TLDR: If you want to jump right into the action, you can head over the accompanying repo. Commits in the repo follow along this article. The master branch shows the final version.

Setup the project

In order for everything to work properly, we simply need a bunch of plugins for managing the project. There are basically three things that we need to do: telling TypeScript what are the types that we are going to provide it, manage the npm dependencies that we want to use, and tell Scala what are the types that exist in JS/TS in the dependencies that we use. Luckily for us, there are exactly three plugins to do just that, to be added inside `project/plugins.sbt`:

addCompilerPlugin(“org.scalameta” % “semanticdb-scalac” % “4.3.10” cross CrossVersion.full)
scalacOptions += “-Yrangepos”
/** Explicitly adding dependency on Scala.js */
addSbtPlugin(“org.scala-js” % “sbt-scalajs” % “1.1.1”)
/** Plugin for generating TypeScript declaration file. */
resolvers += Resolver.jcenterRepo
addSbtPlugin(“eu.swdev” % “sbt-scala-ts” % “0.9”)
/** Plugin for generating Scala.js facades from TypeScript declaration file. */
resolvers += Resolver.bintrayRepo(“oyvindberg”, “converter”)
addSbtPlugin(“org.scalablytyped.converter” % “sbt-converter” % “1.0.0-beta18”)
Antoine Doeraene

Mathematician, Scala enthusiast, father of two.