Add pubnub to angular2 cli project

≡放荡痞女 提交于 2019-12-10 10:31:40

问题


I want to add PubNub to an angular2-cli project. The problem is with the linking; however, I followed the instructions of the pubnub-angular2 package on npmjs.com.

When I try to load it in the browser, the error message is this:

EXCEPTION: PubNub is not in global scope. Ensure that pubnub.js v4 library is included before the angular adapter

In the app.module.ts, I have the following:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';

import {PubNubAngular} from 'pubnub-angular2';
import {AppComponent} from './app.component';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule
    ],
    providers: [PubNubAngular],
    bootstrap: [AppComponent]
})

export class AppModule {}

In the app.component.ts, I have the following code:

import {Component, Injectable, Class} from '@angular/core';
import {PubNubAngular} from "pubnub-angular2";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {

    title = 'Pubnub Chat Service';
    private channel = 'chat-demo-app';

    constructor(private pubnubService: PubNubAngular) {
        pubnubService.init({
            publishKey: 'pub-c-***',
            subscribeKey: 'sub-c-***'
        });
    }

    sendMessage(message: string): void {
        this.pubnubService.publish({
            channel: this.channel,
            message: message
        });
    }

}

Note that if I remove the import in the AppComponent, the component does not see the PubNubAngular provider.

Thanks in advance.


回答1:


From what I can tell from your code the only thing you could possibly be missing is the script tag needed in your index.html, make sure you add this...

<script src="node_modules/pubnub/dist/web/pubnub-angular2.js"></script>

Here is a plunker of pudnub being properly implimented.

plunker

EDIT

all steps to ensure you didnt skip any...

  1. NPM install npm install pubnub

  2. npm install pubnub-angular2

  3. Include script to index.html (see above script

  4. import to app.module import { PubNubAngular } from 'pubnub-angular2';

  5. Add provider to app.module providers: [ PubNubAngular ]

  6. Import to any component using pubnub service import { PubNubAngular } from 'pubnub-angular2';

Angular-cli EDIT

Remove the <script> tag from your index.html and add it to your angular-cli.json file like this...

"scripts": ["../node_modules/pubnub/dist/web/pubnub.js", "./node_modules/pubnub-angular2/dist/pubnub-angular2.js" ],



来源:https://stackoverflow.com/questions/42767132/add-pubnub-to-angular2-cli-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!