SHARE:

Using UnderscoreJs in Angular4 project

I recently introduced UnderscoreJs in a previous article : Introducing UnderscoreJs.

I’m a big fan of  Angular 4 as well, and in this article i will show you how to use UnderscoreJs in Angular 4 (that uses Typescript).

I will show you also how to abstract UnderscoreJs in you Angular 4 in order to decouple as much as possible your from UnderscoreJs.

 

Step 1 :

Create your app and add Underscore as NPM package:

npm install underscore

Step 2 :

We want to abstract Underscore, let’s create a service :

ng g service services/Helper

This command will create the service directory and a prefilled file named helper.service.ts wich look like this :

import { Injectable } from '@angular/core';
@Injectable()
export class HelperService {
constructor() { }
}

Step 3 :

Import Underscore in your service then encapsulate it in custom function (example with each function) :

import { Injectable } from '@angular/core';
import { _ } from 'underscore';

@Injectable()
export class HelperService {

  constructor() { }

  public each(array, delegate) {
    return _.each(array, delegate);
  }

}

Step 4 :

Inject your service into your components like this :

import { Component, OnInit } from '@angular/core';
import { HelperService } from './services/helper.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private _helper: HelperService) { }
}

Step 5 :

To use each function define an array and call the service mwthod previously defined :

import { Component, OnInit } from '@angular/core';
import { HelperService } from './services/helper.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private _fruits = ["Apple", "Banana", "Grapefruit"];

  constructor(private _helper: HelperService) { }

  public ngOnInit() {
    this._helper.each(this._fruits, console.log);
  }
}

Step 6 :

Run your app with

ng serve

and look in the Chrome console for example :

Now you can encapsulate Underscore and many other libraries in your apps 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.