Configuration API for PubNub Angular2 SDK
Angular2 complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Initialization
PubNub Angular2 is a wrapper for the PubNub JavaScript SDK that adds a few extra features to simplify integration with Angular v2 and v4.
- Support: Available to use with TypeScript or plain JavaScript.
- Events: Delegate methods accept the triggerEvents option which will broadcast certain callback and binding these directly to the HTML.
- Autoload: An easy and fast way to retrieve history messages from your channel.
- Multiple instance behavior: All instances are accessible throughout your application via the PubNub service.
You can also use the native PubNub JavaScript SDK if you feel it is more suitable for your situation.
How to use PubNubAngular for Angular4
npm install --save pubnub pubnub-angular2
There are two ways to register PubNubAngular in your list of providers in your Angular App: ngModules
or ngComponents
.
Using your ngModule
Angular Module lets you to use the same instance of PubNub in all Angular Components declared in this. Then you will not need to register PubNub in any Angular Component hosted by the Angular Module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PubNubAngular } from 'pubnub-angular2';
import { AppComponent } from './appComponent';
@NgModule({
imports:[ BrowserModule ],
declarations:[ AppComponent ],
providers:[ PubNubAngular ],
bootstrap:[ AppComponent ]
})
export class AppModule {
constructor() {}
}
Angular Component only lets you use the same instance of PubNub inside itself and its Angular Components children. For more information about this, refer to Dependency Injection and Hierarchical Dependency Injectors
import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>',
providers:[ PubNubAngular ]
})
export class AppComponent {
constructor() {}
}
Now, you can inject PubNubAngular into your ngComponents
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import { Component } from '@angular/core';
import { PubNubAngular } from 'pubnub-angular2';
@Component({
selector: 'appComponent',
template: '<H1>PubNub Angular2 SDK Demo</H1>'
})
export class AppComponent {
constructor(pubnub: PubNubAngular) {
pubnub.init({
publishKey: 'YOUR PUB_KEY',
subscribeKey: 'YOUR SUB_KEY'
});
}
}