All About Multi-Provider Feature of Angular Version 2.0

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Angular JS

Image Source

The newly introduced concept of dependency injection in Angular version 2.0 makes it an attractive front-end technology all because of one amazing feature called 'Multi-Providers'. In general, it allows the users to attach certain operations by themselves and a few plugin custom functionality which is not required in our mobile app use case.

In this article, we are taking a look at what the multi-providers look like, how they function and how Angular takes advantage of it to keep the platform extendible and flexible.

What is a Provider?

A provider is an instruction that depicts how an object is created for a certain token. For instance - You need to have a DataService dependency in an Angular component which looks like this:

 import {DataService} from './data.service';

 @Component (...)

 Class AppComponent {

    constructor (dataService: DataService) {

          //dataService instance of DataService == true 

     }

 }

 

You need to import the type of dependency and annotate a dependency argument with it. After this, Angular is well aware of how to create and inject an object of DataService type according to the provider. This can only happen when the application module is bootstrapping your app or in the component by itself. This way you have various implications regarding the availability and life cycle of the dependency.

 // application module 

 @NgModule ({

    ...

    providers: [

      { provide: DataService, useClass: DataService }

   ]

 })

 

 // or in component 

 @Component({

    providers: [   

      { provide: DataService, useClass: DataService }

    ]

 })

  class AppComponent {}

 

Henceforth, Angular knows how to create objects when you ask for a dependency of type DataService. Basically, there is a shorthand syntax for which we can make use of the useClass instruction to add the same value as of the token in a particular manner:

 

 @NgModule({

   --

   providers: [DataService]

 })

 //or in component

 @Component{(

    providers: [DataService]

 })

 class AppComponent {}

 

What are multi-Providers?

Basically, with the help of multi-providers, you can provide multiple dependencies for a single token. Let us take an instance of how it looks like. The below-given code creates an injector with the multi-providers as given.

 

  const SOME_TOKEN: Opaque Token = new Opaque Token('Some Token');

  var injector = injector.create ([

     { provide:SOME_TOKEN, useValue: 'dependency one', multi: true},

     { provide:SOME_TOKEN, useValue: 'dependency two', multi: true}

  ]);

  

  var dependencies = injector.get(SOME_TOKEN); 

  //dependencies = ['dependency one' , 'dependency two' ]

 

It should be noted here that the users need not create manual injectors and henceforth while creating Angular applications, the platform itself takes care of the same. Due to this reason, it is only used for demonstration purposes.

A token can be a string or a type. We utilize the strings with the goal that we don't take classes to speak to a string an incentive in DI. Yet at the same time, to avoid the blunder messages in the event that something turns out badly, at that point we can likewise make a string token by utilizing OpaqueToken. We do not need to worry about this as the most interesting part of it is to register our providers using the multi: true option. By making use of multi: true, it instructs Angular that the provider is a multi-provider and can offer multiple values for a single token in DI. That’s what we want to do. We have two providers and both have the same tokens with the multiple values. At the point when we request a dependency on a token, we get a total rundown of all the enlisted and given values.

 

You may get a question like why should we provide multiple values for a single token? All things considered, when we register various suppliers with a similar token, the last one successes. For instance - take a look at the given code where only TurboEngine is getting injected as the provider is registered at the last.

 

class Engine {}

class TurboEngine {}

var injector = injector.create ([

   { provide: Engine deps: [] },

   { provide: Engine, useClass: TurboEngine, deps: [] }

]);

var engine = injector.get(Engine);

// engine instance of TurboEngine

 

This indicates that with the help of multi-providers, you can extend the extended thing for any particular token. Also, Angular makes use of such a mechanism for providing pluggable hooks. One of these hooks, for example, are validators. While making a validator, you have to add it to the NG_VALIDATORS multi-supplier as and when required.

 

@Directive ({ 

  selector: '[customValidator][ngModel]';

  providers: [

    provide: NG_VALIDATORS,

    useValue: (formControl) => {

      // validation happens here

    }.

    multi: true

   ]

 })

 class customValidator {}

 

multi-suppliers can't be blended in with the typical suppliers and this bodes well as we can broaden or abrogate a supplier for a token. The Angular stage accompanies a few more multi-suppliers to broaden them without custom code.

TakeAway

multi-providers turn out to be a decent feature for implementing a pluggable interface which is extensible from anywhere. The ultimate disadvantage of multi-providers is that it is only as powerful as the platform provides it. Both the NG_VALIDATORS and NG_ASYNC_VALIDATORS can be actualized straightforwardly into the stage. There is no other way to introduce our own custom multi-providers which depicts what the platform does and this is also not needed. Till then - keep learning!

 


Sponsored:
To find embedded technology information about MCU, IoT, AI etc Check out embedkari.com.


   

Rooney Reeves is a Business Development Executive. Currently working with a Angular Development Company. She always accepts challenges and puts some effort into it. She loves to write and spread her knowledge through writing. Know more about the company from here. Follow her on Twitter.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


AbanteCart - Easy to use open source e-commerce platform, helps selling online

  • e-commerce ecommerce cart

AbanteCart is a free, open source shopping cart that was built by developers with a passion for free and accessible software. Founded in 2010 (launched in 2011), the platform is coded in PHP and supports MySQL. AbanteCart’s easy to use admin and basic layout management tool make this open source solution both easy to use and customizable, depending on the skills of the user. AbanteCart is very user-friendly, it is entirely possible for a user with little to no coding experience to set up and use this cart. If the user would be limited to the themes and features available in base AbanteCart, there is a marketplace where third-party extensions or plugins come to the rescue.

Read More



JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More


RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More


ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More


Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More


Appserver.io – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to appserver.io – the worlds first open source application server for PHP.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


Scene.js - Library to Create Timeline-Based Animation

  • scenejs css timeline javascript animation motion

Scene.js is a JavaScript timeline-based animation library for creating animation websites. As an animated timeline library, it allows you to create a chronological order of movements and positions of objects.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More


LucidWorks Vs SearchBlox - Enterprise Search Solution

  • lucene solr searchblox lucidworks enterprise-search

Enterprise search software should be capable to search the data available in the entire organization or personnel desktop. The data could be in File system, Web or in Database. It should search contents of Emails, file formats like doc, xls, ppt, pdf and lot more. There are many commercial products available but LucidWorks and SearchBlox are best and free.

Read More


Introduction to Apache Cassandra

  • cassandra database nosql

Apache Cassandra was designed by Facebook and was open-sourced in July 2008. It is regarded as perfect choice when the users demand scalability and high availability without any impact towards performance. Apache Cassandra is highly scalable, high-performance distributed database designed to handle large voluminous amounts of data across many commodity servers with no failure.

Read More


10 Free services for your Website / Blog. Just plug it.

  • free website blog free-service free-resources

Each website / blog delivers useful content or service to its users. But website themselves requires some service to monitor and increase its presence. Here are few free services which could be used by Website / Blog. This will be very much helpful for small business owners.

Read More


React Patent Clause Licensing issue. Is it something to worry?

  • react react-license facebook

React libraries from Facebook is one of the most used UI libraries. It is competitive to AngularJS. There are many open source UI components or frameworks available but mostly people narrow down to two choices Angular / React. Recently Facebook has updated React license and added a patent clause which makes companies to worry and rethink whether to use React or not.

Read More


Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More