Helping classes to use Angular2 with CarbonLDP


stars 🌟issues ⚠️updated 🛠created 🐣size 🏋️‍♀️
37Jan 30, 2018Mar 29, 2016Minified + gzip package size for angular2-carbonldp in KB



npm version

Build Status

Helping classes that simplify the integration between Angular2 and CarbonLDP


Install through npm using the following command:

npm install angular2-carbonldp


To use this library, you have to follow three steps:

  1. Initialization of your Carbon context
  2. Provision of the context to your app
  3. Injection of the desired context to your app

1. Initialization

In the bootstrapping file of your Angular2 application (commonly main.ts), you need to initialize the active Carbon's context you are going to use across your application. The contexts with which you can initialize your Carbon instance can be the following:

  • App Context
  • Platform Context

App Context

If your application is going to use only one App Context (which is normally the case), the initialization needs to be as follows:

import { NgModuleRef } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { CARBON_PROTOCOL, CARBON_DOMAIN, DEBUG } from "app/config";
import { appInjector, activeContext } from "angular2-carbonldp/boot";

import { Class as Carbon } from "carbonldp/Carbon";
import { AppModule } from "app/app.module";

let carbon:Carbon = new Carbon();
// Here you can configure this instance of carbon (setSetting, extendObjectSchema, etc.)
// e.g: carbon.setSetting( "domain", CARBON_DOMAIN );

// Initialize carbon with you application context
activeContext.initialize( carbon, "your-app-slug/" );

platformBrowserDynamic().bootstrapModule( AppModule ).then( ( appRef:NgModuleRef<AppModule> ) => {
    // Don't forget this line! It gives guards access to DI
    appInjector( appRef.injector );
} ).catch( ( error ) => {
    console.error( error );
} );

Platform Context

If instead, your web application is going to work with several Carbon App Contexts (an Advanced use), the initialization would be exactly the same but without providing an app slug:

activeContext.initialize( carbon );

2. Provision

After the initialization of your contexts, you can now proceed to provide to your main module the generated contexts. To do this, the provision needs to be as follows:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";

// Providers
import { CARBON_PROVIDERS } from "angular2-carbonldp/boot";
import { CARBON_SERVICES_PROVIDERS } from "angular2-carbonldp/services";

// Components
import { AppComponent } from "./app.component";

@NgModule( {
    imports: [
    declarations: [
    providers: [
        CARBON_PROVIDERS,            // <-- This provides the contexts (App or Platform) to your app 
        CARBON_SERVICES_PROVIDERS,   // <-- This provides the Carbon authentication services to your app
    bootstrap: [ AppComponent ],
} )
export class AppModule { }

3. Injection (DI Objects)

After initializing the context and registering the providers, the following objects can be injected:

import { Inject } from "@angular/core";

import { Class as Carbon } from "carbonldp/Carbon";
import * as App from "carbonldp/App";
import Context from "carbonldp/Context";

import { ContextToken } from "angular2-carbonldp/boot";
import { AuthService } from "angular2-carbonldp/services";

// The main carbon Context
constructor( private carbon:Carbon ) {}

// The App Context (only if you initialized the active context with an app slug!)
constructor( private appContext:App.Context ) {}

// The active context (either carbon or an app context, depending on your initialization).
constructor( @Inject( ContextToken ) private context:Context ) {}

// A basic AuthService that handles cookie based sessions
constructor( @Inject( AuthService.Token ) private authService:AuthService.Class ) {}

Until here, your app is now integrated with Carbon. You can now make use of Carbon inside your app.

But if you want to use Carbon inside the routes of your app, let's say to allow or forbid routes, you can also use the Resolvers and Guards that this library provides.

Resolvers & Guards


Resolvers help you to assure that a desired data will be available before rendering a routed component. This library provides you the following resolver:


Resolver that will make sure the Carbon active context is resolved before activating the route.

It needs a route to redirect the user to in case an error occurs configured in the route data.onError property.

import { Routes } from "@angular/router";
// Resolvers
import { ActiveContextResolver } from "angular2-carbonldp/resolvers";

const appRoutes:Routes = [
        path: "home",
        component: HomeView,
        resolve: {
            activeContext: ActiveContextResolver
        data: {
            onError: [ "/error" ],


Guards help you to continue or block navigation to a given route depending on a condition. All guards need a route to redirect the user to, if the guard rejects the route activation. This route needs to be defined in the route's data.onReject property. We provide you the following two guards:


Guard that will prevent the route from being activated when the user hasn't authenticated himself.

import { Routes } from "@angular/router";
// Guards
import { AuthenticatedGuard } from "angular2-carbonldp/guards";

const appRoutes:Routes = [
        path: "secured",
        component: SecuredView,
        canActivate: [ AuthenticatedGuard ],
        data: {
            onReject: [ "/login" ],
            onError: [ "/error" ],


Guard that will prevent the route from being activated when the user is already authenticated.

import { Routes } from "@angular/router";
// Guards
import { NotAuthenticatedGuard } from "angular2-carbonldp/guards";

const appRoutes:Routes = [
        path: "login",
        component: LoginView,
        canActivate: [ NotAuthenticatedGuard ],
        data: {
            onReject: [ "/secured" ],
            onError: [ "/error" ],


To develop this library you need to have installed the following:

  1. node.js
  2. npm

The steps to develop the library are as follows:

  1. cd to the project path
  2. npm install
  3. gulp to bundle the library
  4. gulp:watch to watch for changes inside the src folder

Gulp tasks

Gulp defines two tasks:

  • default: Runs the build task
  • build: Runs the following tasks: clean:dist, compile:typescript:aot, build:prepare-npm-package
  • compile:typescript: Compiles typescript using the gulp-typescript plugin
  • compile:typescript:aot: Compiles typescript using the @angular/compiler-cli ensuring an AOT compliant library
  • clean:dist: Cleans dist directory
  • build:prepare-npm-package: Prepares publishable npm package inside of the dist directory
  • build:prepare-npm-package:copy:docs: Copies documentation files for the publishable npm package
  • build:prepare-npm-package:copy:package-json: Copies and prepares the package.json file for the publishable npm package
  • watch: Sets up a service to watch for any change to any source file and run the associated tasks to them. Really useful for development
  • watch:typescript: Watches for changes in typescript files (ts)

File structure

├── dist                                        # Compiled files
├── src                                         # Source files
│   ├── guards                                  
│   │   ├── abstract-authentication.guard.ts    # Guard implementing CanActivate
│   │   ├── authenticated.guard.ts              # Guard preventing access to unauthenticated users
│   │   └── not-authenticated.guard.ts          # Guard peventing access to authenticated users
│   ├── resolvers                               
│   │   └── acitve-context.resolver.ts          # Resolver that checks if there's an activeContext
│   ├── services                                
│   │   ├── auth.service.ts                     # Interface and token to use when implementing an Auth Service
│   │   └── carbon-auth.service.ts              # Service implementing the Auth Service usin Carbon 
│   ├── boot.ts                                 # Exports appInjectorFn, CARBON_PROVIDERS and activeContext
│   ├── guards.ts                               # Exports guards
│   ├── index.ts                                # Exports boot, guards, services and resolvers
│   ├── resolvers.ts                            # Exports resolvers
│   └── services.ts                             # Exports services
├── gitignore                                   # Ignore file for git
├── .travis.yml                                 # Travis configuration file
├── CHANGELOG                                   # File to track package changes
├── gulpfile.js                                 # Gulp's tasks definition file
├── package.json                                # npm configuration file
├──                                   # this
└── tsconfig.json                               # Typescript and Angular compiler configuration file.


  • Linting
  • Testing


Copyright (c) 2015-present, Base22 Technology Group, LLC.
All rights reserved.

This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from