Component library (ngx)
ngx-components is a components collection and data access layer for Angular applications. It allows to access our platform from within an Angular application as well as to provide the core components. To achieve this the ngx-components consists of two basic imports:
- core (
@c8y/ngx-components
) which contains all core components like title, navigator or tabs. - api (
@c8y/ngx-components/api
) which enables dependency injection of the @c8y/client services.
The full documentation of all modules and components can be found here.
Prerequisites
If you do not use the @c8y/cli to bootstrap a new application you must first install the package:
$ npm install @c8y/ngx-components
Next, you can add the ngx-components modules to your app module (for example app.module.ts):
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule as ngRouterModule } from '@angular/router';
import { CoreModule, BootstrapComponent, RouterModule } from '@c8y/ngx-components';
@NgModule({
imports: [
BrowserAnimationsModule,
RouterModule.forRoot(),
ngRouterModule.forRoot([], { enableTracing: false, useHash: true }), // 1
CoreModule.forRoot() // 2
],
bootstrap: [BootstrapComponent] // 3
})
export class AppModule {}
- Make sure to set
useHash
navigation to true as the platform does not support pushState - Import the
CoreModule
to allow the use of thec8y-
prefixed components. - Bootstrap your application with the
BootstrapComponent
which will use the<c8y-bootstrap>
component to initialize the root application. Alternatively, you can bootstrap a component of your choice and include that tag into its template or only reuse the given components.
Extension points
To extend and compose an application, ngx-components provide four core architecture concepts called Extensions points:
Content Projection (CP)
This concept allows to project content from one component to another. For example, you can configure the title of a page by setting a <c8y-title>
in any other component. The content of the <c8y-title>
tag is then projected to an outlet component, which is placed in the header bar. The benefit of this concept is that you can place anything into the projected content, for example you can project another custom component into the title.
A good example to use this concept is the c8y-action-bar-item
which uses a routerLink
directive from Angular to route to a different context:
<c8y-action-bar-item [placement]="'right'">
<a class="btn btn-link" routerLink="add">
<i class="fa fa-plus-square"></i> {{'Add' | translate}}
</a>
</c8y-action-bar-item>
The above example gives you an action bar item in the header bar, regardless in which component you define it. If the component is initialized the item is shown and it is removed on destroy.
Multi Provider (MP)
The Multi Provider extension allows a declarative approach to extend the application. Instead of defining it in the template, you extend an already defined factory via a HOOK
. This hook gets executed if the application state changes. The return values are then injected into the page. You can use the normal dependency injection system of Angular and as a result you can usually return an Observable, Promise or Array of a certain type. As an example we can define the tabs of certain routes by hooking into the HOOK_TABS
provider:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Tab, TabFactory, _ } from '@c8y/ngx-components';
@Injectable()
export class ExampleTabFactory implements TabFactory { // 1
constructor(public router: Router) { }
get() {
const tabs: Tab[] = [];
if (this.router.url.match(/world/g)) { // 2
tabs.push({
path: 'world/awesome',
label: 'Awesome',
icon: 'angellist'
} as Tab);
}
return tabs; // 3
}
}
By defining a Injectable()
services which implements the TabFactory
(1) you can define which tabs you want to show on which page. By using the Router
service of Angular we check in this example if the URL of the route contains the name world (2) and only if this matches the tab labeled Awesome
is returned (3). By hooking this into your provider definition of your module you make sure, that the get()
function is checked on each route change:
@NgModule({
declarations: [
/* ... */
],
imports: [
BrowserAnimationsModule,
RouterModule.forRoot(),
ngRouterModule.forRoot([/* ... */], { enableTracing: false, useHash: true }),
CoreModule.forRoot()
],
providers: [
{ provide: HOOK_TABS, useClass: ExampleTabFactory, multi: true} // hook the ExampleTabFactory defined earlier
],
bootstrap: [BootstrapComponent]
})
export class AppModule { }
Usually you use Content Projection within a route and Multi Provider if the context is shared across multiple routes or needs more complex logic to resolve the content. Examples: a title is just valid for one route -> use Content Projection. A tab should only be shown on specific routes under certain conditions -> use Multi Provider. The following hooks are currently supported:
HOOK_TABS
: Allows to show tabs on certain conditions.HOOK_NAVIGATOR_NODES
: Enables navigator nodes to be shown.HOOK_ACTION
: Enables to define the global actions which should be shown or enabled on certain conditions.HOOK_BREADCRUMB
: Can be used to show breadcrumbs in the header bar.HOOK_SEARCH
: Allows to define the search to be shown or not.HOOK_ONCE_ROUTE
: Allows to define a route. Use this if you want to use a context route, for example, add a new tab to the device details view. For all other routes you should use the default Angular router.HOOK_COMPONENTS
: Allows to define a dynamic component to display any kind of component dynamically by referencing its id. To use the component you can use thec8y-dynamic-component
. The most common use case is registration of dashboard widgets.
Services
A service is defined for most components of ngx-components. They can be used via the dependency injection concept of Angular, that means that these services can be injected in the constructor of a component and then add or remove certain UI elements. The following example shows how to use that concept with an alert:
constructor(private alert: AlertService) {
try {
// do something that might throw an exception
} catch(ex) {
this.alert.add({
text: 'Something bad happened!'
type: 'danger';
detailedData: ex;
} as Alert);
}
}
Legacy plugins
If you are extending a default application (Cockpit, Device Management or Administration) you get a file called ng1.ts
. These are so called plugins which haven’t been migrated to Angular yet and are still using angular.js. You can add or remove these plugins to customize the application appearance like it has been done previously in a target file by the addImports: []
or removeImports: []
property. The following shows an example which removes the default import in the angular.js target file:
{
"name": "example",
"applications": [
{
"contextPath": "cockpit",
"addImports": [
"my-plugin/cockpit-home",
],
"removeImports": [
"core/cockpit-home"
]
}
]
}
You get the same result in the new Angular framework by modifying the ng1.ts
file of the cockpit app:
import '@c8y/ng1-modules/core';
// [...] more imports removed for readability
import '@c8y/ng1-modules/alarmAssets/cumulocity.json';
// import '@c8y/ng1-modules/cockpit-home/cumulocity.json'; // 1
import '@c8y/ng1-modules/deviceControlMessage/cumulocity.json';
import '@c8y/ng1-modules/deviceControlRelay/cumulocity.json';
// [...] more imports removed for readability
import 'my-plugin/cumulocity.json'; // 2
As you can see we simply removed the import of the original welcome screen plugin (1.) and replaced it by the custom implementation (2.). Note that all angular.js plugins must have the /cumulocity.json
addition to tell webpack that a legacy plugin is imported.
To use legacy plugins in your custom non-default application you must set the upgrade
flag in the package.json file and use the same import approach like described before:
"c8y": {
"application": {
"name": "myapp",
"contextPath": "myapp",
"key": "myapp-application-key",
"upgrade": true
}
}
Also the module definition of your application must be changed to support these plugins:
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule as NgRouterModule } from '@angular/router';
import { UpgradeModule as NgUpgradeModule } from '@angular/upgrade/static';
import { CoreModule, RouterModule } from '@c8y/ngx-components';
import { UpgradeModule, HybridAppModule, UPGRADE_ROUTES } from '@c8y/ngx-components/upgrade';
import { AssetsNavigatorModule } from '@c8y/ngx-components/assets-navigator';
@NgModule({
imports: [
BrowserAnimationsModule,
RouterModule.forRoot(),
NgRouterModule.forRoot([
...UPGRADE_ROUTES,
], { enableTracing: false, useHash: true }),
CoreModule.forRoot(),
AssetsNavigatorModule,
NgUpgradeModule,
// Upgrade module must be the last
UpgradeModule
]
})
export class AppModule extends HybridAppModule {
constructor(protected upgrade: NgUpgradeModule) {
super();
}
}
That will let your app start in a hybrid mode, which allows to use angular.js and Angular plugins/modules.
To determine which extension points are supported and which concept should be used for certain scenarios the following section gives an overview on all supported components and explains in which case they should be used.
Data access to the platform
The CommonModule
exports the DataModule
, an abstraction of the @c8y/client which allows to use the services of the client with the dependency injection system of Angular. So in any module in which the CommonModule
or DataModule
is imported you can use simple injection to access data of the platform:
import { Component } from '@angular/core';
import { AlarmService } from '@c8y/client'; // 1
@Component({selector: 'app-alerts', template: ''})
export class AlarmComponent {
constructor(private alarmService: AlarmService) {} // 2
async getAllAlarms() {
const alarms = await this.alarmService.list(); // 3
return alarms.data;
}
}
- Import the service from the @c8y/client package.
- Dependency inject that service.
- Use that service to request data from the platform.
For detailed information on all available services and on how to filter and select data refer to @c8y/client.
Client library
The @c8y/client is an isomorphic (node and browser) Javascript client library for the Cumulocity IoT platform API.
Installation
npm install @c8y/client
Usage
Use client.<endpoint>.list()
to request listed data from the Cumulocity IoT REST API and
client.<endpoint>.detail(<id>)
to request detail information. These methods always return a promise. To get an observable use list$
or detail$
.
In the following sections, the default signature of these functions is described. For detailed information, refer to the complete documentation).
Get detail and list data with promises (pull)
Method | Description | Parameters | Return |
---|---|---|---|
detail(entityOrId) |
Request detail data of a specific entity. | entityOrId: string | number | IIdentified : An object which contains an id or an id as number or string. |
Promise<IResult<TData>> : The list as Promise wrapped in an IResult. IResultList contains data and response. |
list(filter) |
Request a list of data with an optional filter. | filter:object : (optional) A filter for query result paging, see Inventory > Query language |
Promise<IResultList<TData>> : The list as Promise wrapped in an IResultList. IResultList contains data, response and paging. |
-
Example for receiving details of one managedObject of the inventory via
detail
:const managedObjId: number = 1; (async () => { const {data, res} = await client.inventory.detail(managedObjId); })();
-
Example for receiving a list of one managedObject of the inventory via
list
:const filter: object = { pageSize: 100, withTotalPages: true }; (async () => { const {data, res, paging} = await client.inventory.list(filter); })();
Accessing a microservice with the Fetch API
The client internally uses the Fetch API. By accessing this core function, you can do any authenticated request to any resource. Standalone you can use core.client.fetch(url, options)
and in @c8y/ngx-components/data
for Angular you simply need to inject the FetchClient
:
constructor(private fetchClient: FetchClient) {} // di
async getData() {
const options: IFetchOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
const response = await fetchClient.fetch('/service/my-service', options); // Fetch API Response
}
All fetch responses can be parsed to JSON if the content type is set correctly. Find more information on handling fetch responses in the MDN documentation.
Authentication strategy
In the Cumulocity IoT platform we currently allow two ways to authenticate:
- Basic Auth: The authentication header is injected into each request.
- Oauth: The client doesn’t know about the authentication header. The header is set in a cookie.
To quickly get you started, the @c8y/client provides a shorthand static function which always uses Basic Auth and verifies the login directly:
await Client.authenticate({ tenant, user, password }), url);
It internally creates a client instance and tries to contact the API to verify if the given credentials are correct. In some cases you must use a more fine-grained authentication, for example, when you don’t know which authentication strategy the user is going to use. In this case you must construct an own instance of the client and pass the authentication strategy to it:
const baseUrl = 'https://acme.cumulocity.com';
const client = new Client(new CookieAuth(), baseUrl); // use here `new BasicAuth()` to switch to Basic Auth
try {
const { data, paging, res } = await client.user.currentUser();
console.log('Login with cookie successful');
} catch(ex) {
console.log('Login failed: ', ex)
}
Subscribe to detail and list data with observables (push)
The detail$
and list$
functions allow to subscribe to realtime channels that omit data on each change:
Method | Description | Parameters | Return |
---|---|---|---|
detail$(entityOrId, options) |
Returns an observable for detail data of one entity | entityOrId: string | number | IIdentified : An object which contains an id or an id as number or string.options: IObservableOptions : (optional) An configuration object to define the observable. |
Observable<TData>> : The list as subscribable observable. |
list$(filter, options) |
Returns an observable for a list of entities. | filter: object : (optional) A filter for query result paging, see Inventory > Query language options: IObservableOptions : (optional) An configuration object to define the observable. |
ObservableList<TData>> : The list as subscribable observable. |
-
Example for receiving details of one managedObject of the inventory via
detail$
:const managedObjId: number = 1; const detail$ = client.inventory.detail$(managedObjId); detail$.subscribe((data) => console.log(data));
-
Example for receiving a list of one managedObject of the inventory via
list$
:const list$ = client.inventory.list$(); list$.subscribe((data) => console.log(data));
Observables can be configured by adding an
IObservableOptions
object with these default properties:{ hot: true, // true = shares one network request realtime: false, // true = listen to real-time changes pagingStrategy: PagingStrategy.PROGRESSIVE, // ALL = All pages are loaded // NONE = only current page is loaded // PROGRESSIVE = load pages with more() realtimeAction: RealtimeAction.FULL, // FULL = use all CRUD realtime actions pagingDelay: 0 // Delay the next page load by x ms realtimeFilter: undefined // A optional additional filter }
Examples
Below some examples are provided which may help you to get started. To see a complex and full implementation of the client into Angular, have a look at @c8y/cli and the new
command to spin up a example application for Angular.
Requesting list data from the inventory:
import { Client } from '@c8y/client';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'demos';
const user = 'user';
const password = 'pw';
(async () => {
const client = await Client.authenticate({
tenant,
user,
password
}, baseUrl);
const { data, paging } = await client.inventory.list();
// data = first page of inventory
const nextPage = await paging.next();
// nextPage.data = second page of inventory
})();
Getting an observable of the inventory endpoint:
import { Client } from '@c8y/client';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'demos';
const user = 'user';
const password = 'pw';
(async () => {
const client = await Client.authenticate({
tenant,
user,
password
}, baseUrl);
client.inventory.list$().subscribe((data) => {
// request inventory data via fetch and adds realtime if data changes
console.log(data);
});
})();
Using realtime:
// realtime event
const subscription = client.realtime.subscribe('/alarms/*', (data) => {
console.log(data); // logs all alarm CRUD changes
});
client.realtime.unsubscribe(subscription);
// realtime observable
const observable$ = client.realtime.observable('/alarms/*');
const observableSubscription = observable$.subscribe((data) => {
console.log(data)); // logs all alarm CRUD changes
});
observableSubscription.unsubscribe();
Authenticate in node.js
The constructor new Client([...])
initializes a new client which allows to request data from the API. Unlike to Client.authenticate([...])
it needs a tenant given and does not verify if the login is correct. This is useful if you are developing a node.js microservice.
const auth = new BasicAuth({
user: 'youruser',
password: 'yourpassword',
tenant: 'acme'
});
const baseUrl = 'https://acme.cumulocity.com';
const client = new Client(auth, baseUrl);
(async () => {
const { data, paging, res }); = await client.inventory.list({ pageSize: 100 });
})();
Application library
The application package (@c8y/apps
) provides example applications for the Web SDK.
Prerequisites
To use the @c8y/apps you must install the @c8y/cli. Refer to its documentation for installation instructions.
Once installed you can run:
$ c8ycli new [your-app-name] [example-name]
For example, to generate the tutorial application with the name my-app
you must run:
$ c8ycli new my-app tutorial
Included applications
The following table provides an overview on the currently supported applications:
Name | Description |
---|---|
application | An empty application to quickly bootstrap new applications. It is the default application and used if you don't specify an [example-name] . |
tutorial | An application that already assembles most of the concepts of the @c8y/ngx-components. Use this to get real code examples. |
cockpit | The Cockpit default application. Use this to extend the existing Cockpit application. |
devicemanagement | The Device Management default application. Use this to extend the existing Device Management application. |
administration | The Administration default application. Use this to extend the existing Administration application. |