Archives by date

You are browsing the site archives by date.

Dockerizing Angular/Web3 app

Web development these days is often more about combining various npm packages then actuall programming. And the packages incompactibility can be extremely frustrating at times. When you add crypto to this mix, it becomes even wilder. Truffle framework promises to ease some problems with deployment of smart contracts, but it introduces other hard-to-debug problems. Recently I started developing small dApp on Angular and I’ve run into yet another issues.

1st issue – can not install web3 on Windows

This is old one, and there is no 100% reliable solution. You will be recommended to install windows-build-tools, but the installation process itself can hang/crash and then you are stuck.

// unfortunatelly this can still fail
npm install --global --production windows-build-tools
node-gyp configure --msvs_version=2015
npm config set python /path/to/executable/python2.7
npm install web3 --save

2st issue – package crypto built in nodejs is not available

The package has been integrated into nodejs from version 11. So if you are using node v10, you will run into trouble as some npm packages depend on it. In order to avoid the hassle with nvm and rebuilding globally installed packages, you can dockerize it.

How to dockerize Angular app?

Add this Dockerfile to the root folder of your project

FROM node:11.1.0

RUN echo node version
RUN node --version

# set working directory
RUN mkdir /usr/src/app
WORKDIR /usr/src/app

# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/app/node_modules/.bin:$PATH

# increment this line when you update the package.json
# otherwise Docker will you cached version of this layer
RUN touch break-cache-15

# install and cache app dependencies
COPY package.json /usr/src/app/package.json
RUN npm install -g @angular/cli
RUN npm install

# add app
COPY . /usr/src/app

# enable crypto package in nodejs
COPY patch.js /usr/src/app/patch.js
RUN node patch.js

# Expose the port the app runs in
EXPOSE 4200

# start app
# the poll option should overcome problem with not working module hot-reload
CMD ng serve --host 0.0.0.0 --poll 1000

And the .dockerignore file to speed things up

node_modules
npm-debug.log
.git

Build the image

docker build -t your-image-name .

And run it

docker run -d --name container-name -v c:\src\path-to-project:/usr/src/app:rw -v /usr/src/app/node_modules -p 4200:4200 your-image-name

Optimize workflow

As you develop, and add/remove npm packages, you will want to re-create docker images and run new versions of container. Repeating the same commands over and over is tedious, so I recommend create aliases or shortcuts. On Windows you can create them with the doskey command. Described fully in this article.

Insert script tags in Angular components

Sometimes you just need to insert 3rd party script tags into Angular Components. It is definitely not very common, and Angular does not make it easy for you. What ever script tag you define your component’s template, will be simply cleared out. Not even a html comment will remain. So I you really need to insert a 3rd party script into your component, you have to do inside the javascript part.

It is actually quite simple. You create a script DOM element, set the src or innerHTML or text property and attach it to the DOM via renderer service.

// 1. import dependencies
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';


// 2. pass then in constructor
constructor(
    private renderer2: Renderer2,
    @Inject(DOCUMENT) private _document
  ) {
  }


// 3. call them in ngOnInit
ngOnInit() {
   const s = this.renderer2.createElement('script');
   s.type = 'text/javascript';
   s.src = 'https://path/to/your/script';
   s.text = ``;
   this.renderer2.appendChild(this._document.body, s);
}

But what if you have scripts, which depend on each other, and have to be called only after the previous ones has been loaded? For example you load affiliate tracker, and you need to initialize it. If you call the initialization code too soon, you will get an error. Luckily you can use the onload property of the script element, and use it to load the dependent scripts. So the final code would look something like this

// 3. call them in ngOnInit - using onload for dependencies
ngOnInit() {
   const s = this.renderer2.createElement('script');
   s.onload = this.loadNextScript.bind(this);
   s.type = 'text/javascript';
   s.src = 'https://path/to/your/script'; // Defines someGlobalObject
   s.text = ``;
   this.renderer2.appendChild(this._document.body, s);
}

loadNextScript() {
   const s = this.renderer2.createElement('script');
   s.text = `
   // This would error, if previous script has not yet been loaded
    someGlobalObject.doSomething();
`
   this.renderer2.appendChild(this._document.body, s);
}

Happy coding. Hope this helped someone

debugging

Convert exponential numbers to decimal form in Javascript

As almost every developers knows, Javascript has notorious problems when working with really big or really small decimal numbers. The reason is floating point. Purpose of this article is not to explain why it behaves the way it does, there are much better resources dedicated just for that. You can read the explanation here or here. There are also various libraries dedicated to working with decimals and precise calculations, such as big.js.

To ilustrate the problem, see the short video below. The input shows the text value, and on the right there is raw value as represented in Javascript. The issue it can cause, is that when Angular (or any other framework for that sake) re-renders the value, it uses the raw value. So the 0.00000001 is replaced with 1e-8. Not very user friendly.

So as a workaround, I’ve written simple utility function. It takes a number and returns correctly formatted string. Be aware that because how Javascript handles decimal numbers, you are not able to represent small fractions in their decimal form. Therefore it has to be represented as a string or some kind of object.

/**
 * Checks if number is in exponential format (eg: 1e-8 for 0.00000001).
 * If it does not, original number is returned.
 * If it does it converts it to string representation of that number
 * which forces it to format 0.00000001
 */
export function convertExponentialToDecimal(exponentialNumber: number): number|string {
  // sanity check - is it exponential number
  const str = exponentialNumber.toString();
  if (str.indexOf('e') !== -1) {
    const exponent = parseInt(str.split('-')[1], 10);
    // Unfortunately I can not return 1e-8 as 0.00000001, because even if I call parseFloat() on it,
    // it will still return the exponential representation
    // So I have to use .toFixed()
    const result = exponentialNumber.toFixed(exponent);
    return result;
  } else {
    return exponentialNumber;
  }

If it helped you solve your problem, let me know in comments below

Angular – .map is not a function

I’ve encountered really weird error. After I’ve removed clearly unused code, our Angular app stopped working. It did however pass lint tests and also the production build passed without problems. The error occurred only during runtime. The error said something like “map is not a function at blablabla” and on the first glance it was totally unrelated to the code where it occurred.

After long digging and googling I found the root cause. Somewhere in our app we used import ‘rxjs/RX’, which imported the whole RxJS library which is large. It has about 50+ operators. And because it was included in the bundle accidentally, the app magically worked. We never had to worry about manually importing the RxJs operators. That is until we fixed the unused and unrelated import, hehe.

Conclusion

So the conclusion is, never import rxjs/RX because it will increase your bundle code size. But include only the specific operators which you really use. You can do it in the main module (usually called the app.module.ts) or specifically in those files, where they are actually used.

 

totally unrelated image :)

My import statement in app.module.ts now looks like this

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/bufferWhen';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publish';
import 'rxjs/add/operator/publishLast';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/operator/withLatestFrom';

Which is much better than this

// never ever!
import 'rxjs/Rx';